How to find the distance between two CG points?

When we do multitouch with two fingers in a UIScrollView, we get two CG points. I want to find the distance between them. Then when again we do the pinch(inside or outside), Then we will again get two points. Then after finding the distance again between these two points , I want to decide whether I pinched in or out. If i have pinched in, surely the new distance will be lesser and vice versa.

But don't know how to find an accurate measurement for the distance between 2 points for doing comparison ? Is anyone having idea about this ?


Solution 1:

You can use the hypot() or hypotf() function to calculate the hypotenuse. Given two points p1 and p2:

CGFloat distance = hypotf(p1.x - p2.x, p1.y - p2.y);

And that's it.

Solution 2:

Distance between p1 and p2:

CGFloat xDist = (p2.x - p1.x);
CGFloat yDist = (p2.y - p1.y);
CGFloat distance = sqrt(xDist * xDist + yDist * yDist);

Put in a function:

func distance(_ a: CGPoint, _ b: CGPoint) -> CGFloat {
    let xDist = a.x - b.x
    let yDist = a.y - b.y
    return CGFloat(sqrt(xDist * xDist + yDist * yDist))
}

Background: Pythagorean theorem

If you only need to calculate if the distance between the points increases or decreases, you can omit the sqrt() which will make it a little faster.