如何检测圆形视图内的触摸

在这里输入图像说明

我有一个四舍五入的UIView。 我只能在紫色的圆圈内检测触摸。 所有在圆外的触摸,例如黑色方块和白色背景都必须忽略。

设置半径和检测触摸将不会有任何用处,因为当多个视图在不同的控制器之上时,将很难pipe理。

有没有办法,我可以做到这一点。 请你能给我一些build议吗?

创buildUIView的自定义子类,说CircularView并重写pointInside:withEvent:方法忽略位于圆外的点。 这个小类的一个对象将是自我包含的,你可以用你想要的任何方式来安排它。

要找出圆形区域是否包含点,可以使用Core Graphics函数CGPathContainsPointCGPathContainsPointcontainsPoint:方法。 这将要求您记住 CGPathRef或表示圆的UIBezierPath对象。 在这个例子中,我假设你已经使用UIBezierPath创build了一个循环path,并且它作为一个属性存储在了CircularView类中。

 @interface CircularView : UIView // initialize this when appropriate @propery (nonatomic, strong) UIBezierPath *circularPath; @end @implementation CircularView - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { return [circularPath containsPoint:point]; } @end 

就是这样。

您可以轻松应用条件触摸如果你有圆的半径。 检查触摸点圆心的距离,检查距离是否小于圆弧半径,否则忽略。

您可以使用以下方法计算距离:

 -(float)distanceWithCenter:(CGPoint)current with:(CGPoint)SCCenter { CGFloat dx=current.x-SCCenter.x; CGFloat dy=current.y-SCCenter.y; return sqrt(dx*dx + dy*dy); } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGFloat radius=5; CGPoint centerOfCircle=CGPointMake(140,200); UITouch *touch=[touches anyObject]; CGPoint touchPoint=[touch locationInView:self.view]; CGFloat distance=[self distanceWithCenter:centerOfCircle with:touchPoint]; if (distance<=radius) { //perform your tast. } } 

为你的圈子创build一个UIView的子类,然后像这样覆盖PointInside:

 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { if (![super pointInside:point withEvent:event]) { return NO; } BOOL isInside = (pow((point.x-self.frame.size.width/2), 2) + pow((point.y - self.frame.size.height/2), 2) < pow((self.frame.size.width/2), 2)) ? YES:NO; return isInside; } 

你可以抛弃'isInside'变种,但这种方法更容易testing。

您可以简单地制作一个button并将其设置为自定义大小,并将其设置为像这样的循环,并且在用户触摸它时,可以将1添加到触摸次数的整数或浮点数。 就那么简单。