简体   繁体   中英

Adding gesture recognizer to UIImage, not UIImageView

I have a UIImageView whose 'View Mode' is set to 'Aspect Fit' in Interface Builder.I want to add gesture recognizer to only my image inside of the UIImageView .To clarify what i say:

I have a UIImageView whose bounds.size.width = 100; and bounds.size.height = 100; and I have a UIImage whose size is 100x50. So, when I add my UIImage to my UIImageView there exists some spaces of 25 from top and 25 from bottom. But I don't want to recognize user's tap when he/she taps on these spaces. I just want to know when user tapped on UIImage .

How can I do that?

You have to add the gesture recognizer to the imageView. What you can do it use the gesture recognize delegate methods:

- gestureRecognizerShouldBegin:
//OR
- gestureRecognizer:shouldReceiveTouch:

You can then figure out where the user tapped in the imageView and compute if the touch landed inside the image in the imageView or outside the image.

You can do this using using the following:

CGPoint tapPoint = [gestureRecognizer locationInView:imageView];
// use tap point to compute if it lands inside the image.

As UIImage extends from NSObject you can not add UITapGestureRecognizer to it, you have to add gesture to the UIImageView itself. Then in any of the UIGestureRecognizer delegate methods:

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;

or

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;

get touch's location in UIImageView . Then by using CGPoint location = [_gesture locationInView:yourImageView] get the touched point, now get the image's frame using this link. Now check if the point is in Image's frame or not by using:

bool CGRectContainsPoint ( CGRect rect, CGPoint point );

This might help you.

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