Calculate the distance between two CGPoints

Viewed 30770

i need to calculate the distance between two CGPoints. I refered this and this, but I don't get it.

11 Answers

In Apple's sample projects, they use hypot. This returns hypothenuse (distance) between two points as explained in this answer.

extension CGPoint {

    func distance(from point: CGPoint) -> CGFloat {
        return hypot(point.x - x, point.y - y)
    }
}
extension CGPoint {
    func magnitude() -> CGFloat {
        return sqrt(x * x + y * y)
    }
    
    func distance(to: CGPoint) -> CGFloat {
        return CGPoint(x: to.x - x, y: to.y - y).magnitude()
    }
}

Euclidean distance to another point with Vision api.

Starting from iOS 14.


import Vision

extension CGPoint {
        
    public func distance(to point: CGPoint) -> Double {
        VNPoint(location: self).distance(VNPoint(location: point))
    }
}


print(CGPoint(x: 1, y: 1).distance(to: .zero)) // 1.4142135623730951

I extended above function to count distance between two CGRects. I count it by counting distance between coners of both CGRects and then returning the smallest distance. I copied function counting intersection point between two lines from:

func distanceBetweenRectangles(r1: CGRect, r2: CGRect) -> CGFloat { // returns distance between boundaries of two rectangles or -1 if they intersect
    let cornerPointsR1: [CGPoint] = [
        CGPoint(x: r1.minX, y: r1.minY),CGPoint(x: r1.minX, y: r1.maxY),CGPoint(x: r1.maxX, y: r1.minY),CGPoint(x: r1.maxX, y: r1.maxY)]
    let cornerPointsR2: [CGPoint] = [
        CGPoint(x: r2.minX, y: r2.minY),CGPoint(x: r2.minX, y: r2.maxY),CGPoint(x: r2.maxX, y: r2.minY),CGPoint(x: r2.maxX, y: r2.maxY)]
    for i in 0..<cornerPointsR1.count {
        if (r2.contains(cornerPointsR1[i])) {
            return -1
        }
    }        
    var distances: [CGFloat] = []
    for i in 0..<cornerPointsR1.count {
        for j in 0..<cornerPointsR2.count {
            distances.append(distanceBetweenPoints(p1: cornerPointsR1[i], p2: cornerPointsR2[j]))
        }
    }
    distances.sort()
    return distances[0]
}
Related