Freddy Benson Freddy Benson - 9 months ago 112
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

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
and then assign the image view to the
property of the
I want to shape, like so:

self.defaultImageView.mask = self.maskImageView

This didn't do anything. It just made
disappear (both image view's added through the storyboard and connected using
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 Source

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.