0

I have a UIImage that contains a mask of another UIImage. The only problem is when I tap the area outside the mask, the script still thinks I'm tapping the image.

let tap = UITapGestureRecognizer() override func viewDidLoad() { super.viewDidLoad() tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:))) tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 let imageMask = UIImageView() imageMask.image = ...//Image to mask to imageMask.frame = imageView.bounds imageView = UIImageView(image: ...) imageView.mask = imageMask imageView.addGestureRecognizer(tap) } @objc func handleTap(_ sender: UITapGestureRecognizer) { print("hello") //prints "hello" when tapped Image outside of mask } 

How to I completely crop the image to the mask, so It won't register taps outside of the mask?

5
  • 1
    could you post the code of the gesture recognizer? Commented Nov 27, 2018 at 13:21
  • You could crop imageView frame, but I can't understand what you mean about "won't register taps outside of the mask"! Commented Nov 27, 2018 at 13:22
  • Yes I add gesture recognizer code @excitedmicrobe Commented Nov 27, 2018 at 13:27
  • I basically want to crop the entire image to the mask, so that you can only tap on the mask and not the area outside of the mask @FrancescoDestino Commented Nov 27, 2018 at 13:28
  • Oh wonderful! So you should use a simple UIView with userInteractionEnabled = true and add the imageView cropped as a subview; so the compiler will trigger only the tapGesture of your imageCropped Commented Nov 27, 2018 at 13:34

1 Answer 1

2

Use this instead two imageViews

let overMask = UIView() overMask.frame = imageView.bounds overMask.isUserInteractionEnabled = true imageView = UIImageView(image: ...) imageView.mask = overMask imageView.addGestureRecognizer(tap) overMask.addSubview(imageView) 
Sign up to request clarification or add additional context in comments.

4 Comments

when I try imageView.crop() I get Value of type 'UIImageView' has no member 'crop';
and when I run the code without .crop() it's the same result of my original code
Yeah sorry i didn't tell you that this should be a new function to crop the imageView :) You should create a new function called crop. How you want to crop the imageView? You want to make a circle? Ora anything else?
I want to crop the imageView to the shape of the mask.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.