我正在使用 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/