Created
October 17, 2020 10:04
-
-
Save xsleonard/92359a239aef0bdd48a7df7aa966df5a to your computer and use it in GitHub Desktop.
Zoom into a specific x-axis range for iOS Charts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For library: https://github.com/danielgindi/Charts | |
extension BarLineChartViewBase { | |
func focusXRange(start: Double, end: Double) { | |
guard end > start else { | |
return | |
} | |
// Reset the zoom back to the full chart view, so that the setVisibleXRange call will zoom in to the desired range, | |
// setVisibleXRange only zooms in, not out. | |
// resetZoom() seems like it should be the right API call, but it doesn't work if the user is already zoomed | |
// in closer than the range to focus. | |
// zoomToCenter(scaleX: 1, scaleY: 1) similarly doesn't work | |
while !isFullyZoomedOut { | |
zoomOut() | |
} | |
let distance = end - start | |
// If the distance to focus on is greater than the xAxis maximum, we can't zoom in any further | |
guard distance < (xAxis.axisMaximum - xAxis.axisMinimum) else { | |
return | |
} | |
// Set the visible range to the distance between start and end. This will zoom the chart in to a range of that distance | |
setVisibleXRange(minXRange: xAxis.axisMinimum, maxXRange: xAxis.axisMinimum + distance) | |
// Move the chart to the start point | |
moveViewToX(start) | |
// Due to the previous setVisibleXRange call, the user cannot zoom back out. | |
// Restore the visible range to the full width of the dataset, so that the user can zoom back out. | |
// Note: this will not zoom the chart back out; setVisibleXRange will only zoom in, not out | |
setVisibleXRange(minXRange: xAxis.axisMinimum, maxXRange: xAxis.axisMaximum) | |
} | |
} | |
// Use it like | |
// chartView.focusXRange(0, 10) // Focus on the first ten data points | |
// chartView.focusXRange(chartView.xAxis.axisMaximum - 10, chartView.xAxis.axisMaximum) // Focus on the last ten data points |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment