CGPath from image

2019-04-02 23:46发布

问题:

I need to create mask based on image (any possible shape). I need to:

  1. Create CALayer with CGPath as a proper mask
  2. Call [UIView.layer setMask: with layer above ]

So main big question is how to set CGPath based on black-white image? Or is it possible to place mask directly from image?

Thanks!


Example image of a mask:

回答1:

You will need to create your image with an alpha channel. According to CALayer's mask property documentation:

An optional layer whose alpha channel is used as a mask to select between the layer's background and the result of compositing the layer's contents with its filtered background.

So the layer you want to use as mask needs an alpha channel. If you want to use an image to create such a channel, the image itself needs to have an alpha channel. So you would need to copy the black and white mask you posted above into the alpha channel of an image. The color of that particular image is ignored. You then load the image, set a layers contents to it and use that layer as a different layers mask. Something around this:

UIImage* imageWithAlphaChannel = [UIImage imageNamed:@"alpha.png"]; // Won't work with jpg
CGImageRef cgImageWithAlpha = [imageWithAlphaChannel CGImage];
CALayer* maskingLayer = [CALayer layer];
maskingLayer.contents = (id)cgImageWithAlpha;

//Assume viewToBeMasked is the view, who's layer needs to be masked
CALayer* layerToBeMasked = viewToBeMasked.layer;
layerToBeMasked.mask = maskingLayer;
maskingLayer.frame = layerToBeMasked.bounds;
//Alternativly use: viewToBeMasked.layer.mask = maskingLayer;

Coded in the browser, excuse systactical errors.

Storing all your masks as png files might blow your app size. You could store the masks as jpgs and create the appropriate alpha version at runtime using the CoreGraphics drawing functions. But that is another question.....



回答2:

Very similar issue I think to something I did a while back. Basically, you'll need to export the file from Adobe Illustrator then run a routine to convert that file into a CGPath.

You'll find how to do it in my answer to this question:

How to detect/handle touch events on curved regions?