简体   繁体   中英

Crop UIImageView and gesture recognizer

I have ImageView that I crop to circle with this:

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. 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 ). In the UIImageView subclass add the following code to create the mask, and create a property, shape, in the .h file.

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,

-(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
    }
}
  1. Set your class conforms to UIGestureRecognizerDelegate
  2. Set your gesture delegate to self
  3. 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;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM