7

I can't find anything in the docs that indicates whether a single CALayer (or subclass) can be used as the mask property for multiple other layers. Is it possible? Or undefined?

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • Bizarrely you can NOT do this. Each layer has to have it's own mask layer! If you have to use the same mask, you indeed have to duplicate it ! – Fattie Sep 28 '19 at 23:17

2 Answers2

3

My experimentation says that it cannot. It will end up as the mask for the last layer it is attached to, and any previous layers it was assigned as a mask to, will revert to the default value of mask.

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
1

It is possible. I combined mask of CAGradationLayer and CAShapeLayer.

I made UIImage from two layers, and I use it to mask.

You can generate image from CALayer like below.

extension CALayer {
    func makeImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        self.renderInContext(UIGraphicsGetCurrentContext())
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

and You can mask by multiple layers.

firstMask.mask = secondMask
let img = firstMask.makeImage()// require firstMask.frame

let combinedMask = CALayer()
combinedMask.frame = CGRectMake(0,0, img.size.width, img.size.height)
combinedMask.contents = img.CGImage

yourLayer.mask = combinedMask
taku_oka
  • 453
  • 6
  • 18