iOS layer mask from UIImage/CGImage?

2019-09-11 06:17发布

问题:

I have the following image:

On a UIImageView of the exact same frame size, I want to show everything but the red fill.

        let mask = CALayer()
        mask.contents = clippingImage.CGImage
        self.myImageView.layer.mask = mask

I thought the black color would show through when applied as a mask, but when I set the mask the whole view is cleared. What's happening here?

回答1:

When creating masks from images, you use the Alpha channel, rather than any RGB channel. Even if your mask is black, you need to set its Alpha value to 0, as the mask pays attention only to Alpha channel. Any by default black is [0,0,0,255] in terms of RGBA. If you load RGB, it will of course convert it into RGBA with A = 1.