Mask CALayer with Another CALayer

584 views Asked by At

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?

1

There are 1 answers

0
tikhop On BEST ANSWER

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.