Can one CALayer be used as a mask for several other layers?

I can't find anything in the docs that indicate if one CALayer (or subclass) can be used as a property mask

for multiple other layers. Is it possible? Or undefined?

+3


source to share


2 answers


My experiments say that this is impossible. It will be created as a mask for the last layer to which it is attached, and any previous layers that it was assigned as a mask will revert to the default mask value.



+2


source


It is possible. I have combined the CAGradationLayer mask and the CAShapeLayer.

I made UIImage

from two layers and I use it for masking.

You can create images from CALayer as shown below.



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

      

and you can mask 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

      

+1


source







All Articles