[英]Crop UIImageView and gesture recognizer
我有ImageView,我想以此来圈出:
self.contentMode = UIViewContentModeScaleAspectFill;
self.layer.cornerRadius = self.bounds.size.height / 2.0;
self.layer.masksToBounds = YES;
然后我向其中添加了手势识别器,但是它会在裁剪区域触发。
如何避免在种植区域开火?
遮罩图像的一种更通用,更灵活的方法是使用CAShapeLayer。 您可以创建任何形状(包括圆形)以用作蒙版。 通过使用这种方法来裁剪图像视图而不是使用cornerRadius
,您可以检查接触点是否在图层的路径( UIBezierPath
)内。 在UIImageView
子类中,添加以下代码以创建蒙版,并在.h文件中创建形状属性。
self.shape = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = self.shape.CGPath;
self.layer.mask = shapeLayer;
在控制器中,添加点击手势识别器,并在其action方法中使用此代码,
-(void)handleTap:(UITapGestureRecognizer *) tapper {
CGPoint touchPoint = [tapper locationInView:tapper.view];
if ([self.imageView.shape containsPoint:touchPoint]) {
NSLog(@"touched");
// do what you want with the touch here
}
}
UIGestureRecognizerDelegate
然后使用此委托来确定是否要触发
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
范例程式码
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
CGPoint touchPoint = [touch locationInView:self.imageview];
if (CGRectContainsPoint(self.imageview.bounds, touchPoint)) {
CGFloat centerX = CGRectGetMidX(self.imageview.bounds);
CGFloat centerY = CGRectGetMidY(self.imageview.bounds);
CGFloat radius2 = pow((touchPoint.x -centerX),2)+ pow((touchPoint.y - centerY), 2);
if (radius2 < pow(CGRectGetWidth(self.imageview.frame)/2, 2)) {
return YES;
}
}
return NO;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.