开发者

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 represent开发者_如何学Cs the distance between these points. How can I accomplish this?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜