Freddy Benson Freddy Benson - 1 month ago 14
Swift Question

What do I need for masking a UIImageView and how do I do it in Swift 3?

I was wondering what I would need if I wanted to use a mask image to get my

UIImageView
in a specific shape. From what I understand, to create a mask, I need to have an image with the shape of the mask all black on top of a white background. Something like this, for example:

Star-shaped mask image

First of all, is this sufficient to shape an image view, and if so, how do I do it in Swift 3? I can only find masking code that is either outdated or written in Objective-C. I've tried simply assigning the image above to an
UIImageView
and then assign the image view to the
mask
property of the
UIImageView
I want to shape, like so:

self.defaultImageView.mask = self.maskImageView


This didn't do anything. It just made
self.maskImageView
disappear (both image view's added through the storyboard and connected using
IBOutlet
properties). I'm sure I'm forgetting to do something. It can't be this simple. I would appreciate it if someone could help me out. Like I said, I put both image views on the exact same spot, on top of each other, in the storyboard.

Answer

You should use a png image, which supports transparency, unlike jpg.

In Photoshop your image should look similar to this:

enter image description here

It doesn't matter if your shape is black or white. What matters is transparency of each pixel. Opaque area (black in this case) will be visible and transparent area will get trimmed.

Comments