Skip to content

Instantly share code, notes, and snippets.

@xsleonard
Created October 17, 2020 10:04
Show Gist options
  • Save xsleonard/92359a239aef0bdd48a7df7aa966df5a to your computer and use it in GitHub Desktop.
Save xsleonard/92359a239aef0bdd48a7df7aa966df5a to your computer and use it in GitHub Desktop.
Zoom into a specific x-axis range for iOS Charts
// 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