What do I need to mask a UIImageView and how to do it in Swift 3?

I was wondering what I would need if I wanted to use a mask image to get a UIImageView in a specific form. From what I understand, in order to create a mask, I need to have an image with the shape of a mask black on a white background. Something like this, for example:

Star shaped image

First of all, is it enough to form a representation of the image, and if so, how to do it in Swift 3? I can only find masking code that is either deprecated or written in Objective-C. I tried just assigning the image above the UIImageView , and then assigning the image type to the mask property of the UIImageView that I want to generate, for example:

 self.defaultImageView.mask = self.maskImageView 

It did nothing. He simply deleted self.maskImageView (both images were added through the storyboard and connected using the IBOutlet properties). I'm sure I forget to do something. It can't be that simple. I would be grateful if someone could help me. As I said, I put both images in the same place on top of each other in the storyboard.

UPDATE: My first attempt to set the mask programmatically after removing it from my storyboard.

 let layer:CALayer = CALayer() let mask:UIImage = UIImage(named: "Black-Star-Photographic-Agency")! layer.contents = mask layer.frame = CGRect(x: 0, y: 0, width: ((self.defaultImageView.image?.size.width)!), height: (self.defaultImageView.image?.size.height)!) self.defaultImageView.layer.mask = layer self.defaultImageView.layer.masksToBounds = true 

As a result, the image completely disappeared and was no longer visible. Am I doing something, am I forgetting something, or both?

+5
source share
2 answers

You must use a png image that supports transparency, unlike jpg.

In Photoshop, your image should look something like this:

enter image description here

It doesn't matter your figure is black or white. The transparency of each pixel is important. The opaque area (black in this case) will be visible, and the transparent area will be cropped.

Edit:

If you do this, you should not create masks from the storyboard. This will not be part of your hierarchy of views. Just add it programmatically as follows:

 let maskView = UIImageView() override func viewDidLoad() { super.viewDidLoad() maskView.image = UIImage(named: "mask") imageView.mask = maskView } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() maskView.frame = imageView.bounds } 

Output:

enter image description here

Here is a test project showing how it works.

+10
source

Also, if you use a custom frame / image and run a mask that does not display correctly, try adjusting the content mode of the mask:

 maskView.contentMode = .scaleAspectFit 
0
source

Source: https://habr.com/ru/post/1258627/


All Articles