简体   繁体   English

使用另一个CALayer屏蔽CALayer

[英]Mask CALayer with Another CALayer

I'm trying to mask one CALayer(newSticker) with the image of another layer(stickerMask), like so: 我正在尝试用另一层(stickerMask)的图像遮罩一个CALayer(newSticker),如下所示:

    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. 如果我在我的“ picturesView”图层中单独添加stickerMask,它将正确加载到屏幕上,并且newSticker将加载相应的自定义背景色。

My problem is that once you apply stickerMask to newSticker.mask, nothing appears at all. 我的问题是,一旦将stickerMask应用于newSticker.mask,则什么也不会出现。 I have tried setting masksToBounds to both false and true, but get the same result. 我尝试将masksToBounds设置为false和true,但是得到相同的结果。

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. 换句话说,掩模的坐标系等于上层坐标系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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