简体   繁体   中英

Mask CALayer with Another CALayer

I'm trying to mask one CALayer(newSticker) with the image of another layer(stickerMask), like so:

    func placeSticker(location: CGPoint) {

    let stickerMask = CALayer()
    stickerMask.contents = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("brush\(self.stickerSelected).png"))!.CGImage
    stickerMask.frame = CGRect(x: location.x * 100, y: location.y * 100, width: 200, height: 200)

    let newSticker = CALayer()
    newSticker.backgroundColor = UIColor(red: self.red, green: self.green, blue: self.blue, alpha: 1.0).CGColor
    newSticker.frame =
        CGRect(x: location.x * 100, y: location.y * 100, width: 200, height: 200)
    newSticker.mask = stickerMask
    self.picturesView.layer.addSublayer(newSticker)

}

If I add stickerMask by itself in my "picturesView" layer, it loads onto the screen properly, and newSticker will load up with the corresponding custom background color.

My problem is that once you apply stickerMask to newSticker.mask, nothing appears at all. I have tried setting masksToBounds to both false and true, but get the same result.

Any ideas of what I'm doing wrong?

The problem is with frame calculation of the mask.

Make sure that when some of the layer is a mask then you should calculate the frame of the mask like if it is just a sublayer of the superlayer.

In other words, the coordinate system of the mask equals to the superlayer coordinate system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM