Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xcode

ios

touch

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?

like image 245
Mike Cadigan Avatar asked Dec 12 '22 13:12

Mike Cadigan


1 Answers

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:

  • UIResponder Class Reference
  • UITouch Class Reference

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

like image 184
John Parker Avatar answered Dec 15 '22 03:12

John Parker