override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true
if let touch = touches.first{
let currentPoint = touch.location(in: self.view)
drawLines(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
segmentTop = touch.location(in: self.view)
segmentBottom = touch.location(in: self.view)
segmentLeft = touch.location(in: self.view)
segmentRight = touch.location(in: self.view)
}
}
我目前正在从事一个项目,我的目标是围绕绘图裁剪一个片段。为此,我必须检查触摸位置,以便我可以输出触摸最接近每个边缘的位置。例如,段的顶部将是触摸位置最接近顶部边缘的位置,这就是我试图输出的内容,但是我没有什么可以基于它。这有点像在游戏中打高分,而在这里你没有以前的高分作为基础。
您的问题并不完全清楚,但我认为您正在寻找一种方法来跟踪最后一个接触点的最小和最大 X 以及最小和最大 Y。
一种解决方案是这样的:
声明属性以跟踪当前最小值和最大值 X 和 Y 值:
var minX: CGFloat?
var maxX: CGFloat?
var minY: CGFloat?
var maxY: CGFloat?
然后,对于每个接触点,您可以比较每个接触点:
if let minX = minX {
// See if this new point is less than the current min
if lastPoint.x < minX {
self.minX = lastPoint.x
}
} else {
// No current minX so use this value
self.minX = lastPoint.x
}
对其他三个值执行类似的计算。
一个更简单但类似的解决方案是从初始值开始并避免使用可选:
var minX = CGFloat.greatestFiniteMagnitude
var maxX = CGFloat.leastNormalMagnitude
var minY = CGFloat.greatestFiniteMagnitude
var maxY = CGFloat.leastNormalMagnitude
然后每个检查变为:
if lastPoint.x < minX {
minX = lastPoint.x
}
if lastPoint.x > maxX {
maxX = lastPoint.x
}
对 Y 值重复此操作。
试试这个
segmentTop = max(segmentTop, touch.location(in: self.view).y)
segmentBottom = min(segmentBottom, touch.location(in: self.view).y)
segmentLeft = min(segmentLeft, touch.location(in: self.view).x)
segmentRight = max(segmentRight, touch.location(in: self.view).x)
确保 segmentTop、segmentBottom、segmentLeft 和 segmentRight最初设置为 0