Reverse a CALayer mask

人盡茶涼 提交于 2019-12-04 06:07:19

What I would do is construct the mask in real time. This is easy if you have a black image of the logo. Using standard techniques, you can draw the logo image into an image that you construct in real time, so that you are in charge of the size of the image and the size and placement of logo within it. Using a "Mask To Alpha" CIFilter, you can then convert the black to transparent for use as a layer mask.

So, to illustrate. Here's the background image: this is what we want to see wherever we punch a hole in the foreground:

Here's the foreground image, lying on top of the background and completely hiding it:

Here's the logo, in black (ignore the grey, which represents transparency):

Here's the logo drawn in code into a white background of the correct size:

And finally, here's that same image converted into a mask with the Mask To Alpha CIFilter and attached to the foreground image view as its mask:

Okay, I could have chosen my images a little better, but this is what I had lying around. You can see that wherever there was black in the logo, we are punching a hole in the foreground image and seeing the background image, which I believe is exactly what you said you wanted to do.

The key step is the last one, namely the conversion of the black-on-white image of the logo (im) to a mask; here's how I did that:

    let cim = CIImage(image:im)
    let filter = CIFilter(name:"CIMaskToAlpha")!
    filter.setValue(cim, forKey: "inputImage")
    let out = filter.outputImage!
    let cgim = CIContext().createCGImage(out, from: out.extent)
    let lay = CALayer()
    lay.frame = self.iv.bounds
    lay.contents = cgim
    self.iv.layer.mask = lay
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!