Swift charts - highlight center point

Viewed 636

I am using https://github.com/danielgindi/Charts for creating a chart. After user scrolls the chart, I wanted to get the data point closest to the middle of the chart:

        let currentMinX = self.chartView.lowestVisibleX
        let currentMaxX = self.chartView.highestVisibleX
        let midX = currentMinX + (currentMaxX - currentMinX)/2

        let currentMinY = self.chartView.chartYMin // y is not scrollable, so I can use it
        let currentMaxY = self.chartView.chartYMax
        let midY = currentMinY + (currentMaxY - currentMinY)/2

        let midPoint = CGPoint(x: midX, y: midY)

        let closestPoint = chartView.getHighlightByTouchPoint(midPoint)
        print("\(closestPoint?.x ?? 0)-\(closestPoint?.y ?? 0)")

Unfortunately closestPoint is the closest to the lower-left corner of the visible area, not the one closest to the middle. Why is that? Debugging movie: https://youtu.be/YTYqt5o6ifQ

EDIT: Apparently the transformer was returning the wrong value: I've fixed it by changing the Transformer's method:

 @objc open func valueForTouchPoint(x: CGFloat, y: CGFloat) -> CGPoint
    {
        return CGPoint(x: x, y: y)//CGPoint(x: x, y: y).applying(pixelToValueMatrix)
    }
1 Answers

getHighlightByTouchPoint expects the point in view coordinate system. (same as valueForTouchPoint) And your (midX, midY) point is in chart coordinate system. Probably that is the main reason why you get incorrect result. If so, you can replace your code with this:

    // if you have any additional insets, for chart area in the view, 
    // change calculation of this point to make it point to the middle of the chart area
    let midPoint = CGPoint(x: self.chartView.bounds.midX, y: self.chartView.bounds.midY) 
    let closestPoint = chartView.getHighlightByTouchPoint(midPoint)

Upd: Replaced frame with bounds for more correct implementation in different situations

Related