我有一个圆形的UIView。我必须只在紫色圆圈内检测触摸。所有在圆外的触摸,例如黑色正方形和白色背景,必须被忽略。
设置半径并检测触摸将没有任何用处,因为当多个视图重叠在一起并且具有不同的控制器时,管理将变得困难。
是否有办法解决这个问题?请给我一些建议。
我有一个圆形的UIView。我必须只在紫色圆圈内检测触摸。所有在圆外的触摸,例如黑色正方形和白色背景,必须被忽略。
设置半径并检测触摸将没有任何用处,因为当多个视图重叠在一起并且具有不同的控制器时,管理将变得困难。
是否有办法解决这个问题?请给我一些建议。
CircularView
的自定义子类,并覆盖 pointInside:withEvent:
方法,以忽略位于圆形外部的点。这个子类的对象将是自包含的,你可以按照自己的想法进行排列。CGPathContainsPoint
或 UIBezierPath
中的 containsPoint:
方法。这将需要你记住表示圆形的 CGPathRef
或 UIBezierPath
对象。在这个例子中,我假设你使用 UIBezierPath
创建了一个圆形路径,并将其存储为 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
就是这样。
CircularView
类中的背景设置为 clearColor
。 - Anurag如果您有圆的半径,可以轻松应用条件来触摸。检查触摸点与圆心之间的距离,检查距离是否小于圆的半径,然后处理触摸,否则忽略它。
您可以使用以下方法计算距离:
-(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.
}
}
- (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;
}