Mike Cadigan
Mike Cadigan

Reputation: 41

How exactly do I output the distance between two touch points in Xcode for iOS?

Here is my goal: to have a user touch two different points on the screen, and the app will output a number that represents the distance between these points. How can I accomplish this?

Upvotes: 4

Views: 8629

Answers (2)

John Parker
John Parker

Reputation: 54445

At a simple level, you could simply use a pythagorean theorem approach as follows to calculate the distance between the two points.

double distance = sqrt(pow((x2 - x1), 2.0) + pow((y2 - y1), 2.0));

I presume you're using a - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event method (after registering as a UIResponder and receiving multiple touches via [self setMultipleTouchEnabled:YES];), in which case you can extract the CGPoint's .x and .y values by extracting the provided UITouches from the NSSet and using the locationInView method to obtain the CGPoint for the touch in question.

If you've not used these classes before, I'd be tempted to read up on:

However, if you've not yet used such things before, I'd also recommend a read of the Event Handling Guide for iOS documentation to give you a good grounding. (You might also want to take a step back and consume the Creating an iPhone Application docs, as these go into quite a bit of detail (along with source code) as to how you can capture touch events, etc.)

Upvotes: 11

B_.
B_.

Reputation: 2254

When you receive a touch event, you get its xy coordinates. You can use that formula we all learned in grade school, d = sqrt((x_2 - x_1)^2 + (y_2 - y_1)^2)). This will get you the distance in pixels between them. The iphone4 has 326 ppi so divide the distance you get by 326 and you get an estimate of the distance between touches in inches.

Upvotes: 2

Related Questions