[英]Crop UIImageView and gesture recognizer
I have ImageView that I crop to circle with this: 我有ImageView,我想以此来圈出:
self.contentMode = UIViewContentModeScaleAspectFill;
self.layer.cornerRadius = self.bounds.size.height / 2.0;
self.layer.masksToBounds = YES;
Then I added gesture recognizer to it, but it fires in cropped area. 然后我向其中添加了手势识别器,但是它会在裁剪区域触发。
How can I avoid firing it in cropped area? 如何避免在种植区域开火?
A more general and flexible way to mask your image is with a CAShapeLayer. 遮罩图像的一种更通用,更灵活的方法是使用CAShapeLayer。 You can create any shape, including a circle, to use as a mask.
您可以创建任何形状(包括圆形)以用作蒙版。 By using this approach to crop your image view instead of using
cornerRadius
, you can check if the touch point is within the layer's path (a UIBezierPath
). 通过使用这种方法来裁剪图像视图而不是使用
cornerRadius
,您可以检查接触点是否在图层的路径( UIBezierPath
)内。 In the UIImageView
subclass add the following code to create the mask, and create a property, shape, in the .h file. 在
UIImageView
子类中,添加以下代码以创建蒙版,并在.h文件中创建形状属性。
self.shape = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = self.shape.CGPath;
self.layer.mask = shapeLayer;
In the controller, add the tap gesture recognizer, and use this code in its action method, 在控制器中,添加点击手势识别器,并在其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
UIGestureRecognizerDelegate
Then use this delegate to decide that if you want it fire or not 然后使用此委托来确定是否要触发
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
Example Code 范例程式码
-(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.