Swift 3: Distance between two CGPoints

Swift 3: Distance between two CGPoints

Here it is in Swift 3, it’s a little different. I tried to use hypotf but it didn’t like CGFloat subtraction.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        let pointCenter = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
        let touchPoint = touches.first?.location(in: self.view)
        let distance = CGPointDistance(from: pointCenter, to: touchPoint! )
        print("distance: \(distance)")
    }
    super.touchesBegan(touches, with: event)
}
    
func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat {
    return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)
}
    
func CGPointDistance(from: CGPoint, to: CGPoint) -> CGFloat {
    return sqrt(CGPointDistanceSquared(from: from, to: to))
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.