4

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?

Mike Cadigan
  • 41
  • 1
  • 2

2 Answers2

11

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.)

John Parker
  • 54,048
  • 11
  • 129
  • 129
  • Thanks for the reply. I'm new at this; Ive only created soundboards before. This is my first real application. Do you know where I can find a tutorial for this? – Mike Cadigan Apr 27 '11 at 20:08
  • @Mike I've updated my answer with some additional references which should hopefully help. (You might also want to take a step back and consume the [Creating an iPhone Application](http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Creating_an_iPhone_App/_index.html#//apple_ref/doc/uid/TP40007595) docs, as this goes into quite a bit of detail (along with source code) as to how you can capture touch events, etc.) – John Parker Apr 27 '11 at 21:18
2

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.

B_.
  • 2,164
  • 2
  • 17
  • 20