计算CGPoint从一个地方到另一个地方的距离

时间:2016-09-06 15:46:59

标签: macos swift2 mouseevent cgpoint

我有什么方法可以用来计算CGPoint从旧位置到新位置的距离?

var point: CGPoint = CGPointMake(x:50.0, y:50.0)

并且有一种使用LMB拖动点的方法:

func mouseDragged(event: NSEvent) {

    var pointDragged = self.convertPoint(event.locationInWindow, fromView: nil)
}

enter image description here

1 个答案:

答案 0 :(得分:1)

使用Pythagorean theoremmouseLocation = event.mouseLocation(),您的案例event的类型为NSEvent

let point1: CGPoint = CGPoint(x: 2.0, y: 9.0)
let point2: CGPoint = CGPoint(x: 4.0, y: 13.0)

let xDist = (point1.x - point2.x)
let yDist = (point1.y - point2.y)
let distance = sqrt((xDist * xDist) + (yDist * yDist))

print(distance)

point1将是您的起始位置,您可以从point2函数中的NSEvent获取用户点击的位置mouseDragged

mouseLocation = event.mouseLocation()
point2 = CGPointMake(mouseLocation.x, mouseLocation.y)