如何检测特定区域的触摸

6

目前我看到一个触摸事件会显示触摸发生的UIView。但是如果我需要检测某些非矩形形状的触摸,比如一个圆形,该怎么办?

基本上,我只想在用户触摸不可见的圆形区域内做一些事情。

任何帮助/指导都将不胜感激,谢谢!

1个回答

7
你可以这样做。请注意,“locationInView”将返回与指定视图相关的触摸坐标,因此在视图的左上角触摸将始终返回(0,0),无论该视图在屏幕上的位置如何。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{   
  UITouch *touch = [touches anyObject];

  // gets the coordinats of the touch with respect to the specified view. 
  CGPoint touchPoint = [touch locationInView:self];

  // test the coordinates however you wish, 
  ...
}

要针对一个球进行测试,您需要计算触摸点到球心的距离,然后检查这是否小于球半径。


谢谢安德鲁!有没有关于如何确定一些非标准形状的提示?我猜这可能类似于使用CGContext绘制一个形状,然后以某种方式进行检查?或者是什么? - dizy
你可以使用CGContext进行绘图,但是对于“IsInside”计算,你只能使用数学。如果你可以将形状表示为多边形,那么这就很简单了。这个链接可能会有所帮助: http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ - Andrew Grant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接