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

Freddy Benson picture Freddy Benson · Oct 22, 2016 · Viewed 10k times · Source

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.

UPDATE: My first attempt to set the mask programmatically after deleting 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

The result was that the image view had completely disappeared and wasn't visible anymore. Am I doing something, am I forgetting something or both?

Answer

alexburtnik picture alexburtnik · Oct 22, 2016

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.

Edit:

You should not create mask view from storyboard if you do so. It is not going to be a part of your view hierarchy. Just add it programmatically like this:

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 to show how it's working.