Swift 图表 - 突出显示中心点

标签 swift charts

我正在使用 https://github.com/danielgindi/Charts用于创建图表。 用户滚动图表后,我想获取最靠近图表中间的数据点:

        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)")

不幸的是,closestPoint 是距离可见区域左下角最近的点,而不是距离中间最近的点。这是为什么? 调试影片:https://youtu.be/YTYqt5o6ifQ

编辑: 显然,转换器返回了错误的值: 我通过更改 Transformer 的方法修复了它:

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

最佳答案

getHighlightByTouchPoint 需要 View 坐标系中的点。 (与 valueForTouchPoint 相同)并且您的 (midX, midY) 点在图表坐标系中。这可能是您得到错误结果的主要原因。如果是这样,你可以用这个替换你的代码:

    // 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)

更新:将frame替换为bounds,以便在不同情况下更正确地实现

关于Swift 图表 - 突出显示中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666001/

相关文章:

arrays - SWIFT 解析问题

javascript - 我的右轴被切断了……我该如何纠正它?

iOS App 在 iOS 12 上的编译器生成代码中崩溃

ios - "Restore purchases"对于绑定(bind)帐户的内容是必需的吗?

ios - 如何获取待处理的UNNotificationRequest的剩余时间?

Javascript 图表库

C# 图表从数据表中添加多个系列

javascript - 倾斜的 Highcharts 轴标签与图例重叠

excel - 精确的流程事件时间线图(例如在 Excel 中)

ios - 从字符串中获取特定值并创建数组