如何在 Xcode for iOS 中输出两个触摸点之间的距离?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5809422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How exactly do I output the distance between two touch points in Xcode for iOS?
提问by Mike Cadigan
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?
这是我的目标:让用户触摸屏幕上的两个不同点,应用程序将输出一个代表这些点之间距离的数字。我怎样才能做到这一点?
回答by John Parker
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.
我想你正在使用- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
方法(注册为UIResponder和经由接收多个触摸后[self setMultipleTouchEnabled:YES];
),在这种情况下,可以提取出CGPoint
的.x
和.y
通过提取所提供的值UITouch从NSSet中ES和使用该locationInView
方法来获得CGPoint
针对触摸问题。
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 iOSdocumentation to give you a good grounding. (You might also want to take a step back and consume the Creating an iPhone Applicationdocs, as these go into quite a bit of detail (along with source code) as to how you can capture touch events, etc.)
但是,如果您以前从未使用过这些东西,我还建议您阅读iOS文档的事件处理指南,以便为您打好基础。(您可能还想退后一步并使用创建 iPhone 应用程序文档,因为这些文档包含有关如何捕获触摸事件等的大量细节(以及源代码)。)
回答by B_.
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.
当您收到触摸事件时,您会得到它的 xy 坐标。你可以使用我们在小学都学过的那个公式,d = sqrt((x_2 - x_1)^2 + (y_2 - y_1)^2))
。这将为您提供它们之间的像素距离。iphone4 有 326 ppi,所以将你得到的距离除以 326,你就可以估计出触摸之间的距离(以英寸为单位)。