Dear stack overflow community,
I have a problem concerning the mask property of a CAShapeLayer
in iOS (Swift).
What I am trying to achieve is an eraser that erases parts of a image-layer by masking it. The problem comes in, when I try to invert it.
I found some good answers on inverting a path, but these were only useful when using a filled path. What I try to do is stroke a path and use the inverted one to mask an image. The line width on the stroke should by around 30.0
so it looks like an eraser.
I tried different things. My current version looks like this:
- Create a
CAShapeLayer
which holds the path of the eraser-stroke - Set the
fill-color
of the layer tonil
- Set the
stroke-color
andline width
- Add the layer as the mask of the image-layer
This is working fine, but it only makes the parts of the image visible that are within the stroke. I want to do it reversed. I thought of a black and white mask, but this does not work, because the mask is delivered through the alpha channel.
Does anyone has an idea how to solve the problem?
You can achieve this by drawing with transparent colors to a non-opaque layer. This can be done by using another blend mode for drawing. Unfortunately
CAShapeLayer
doesn't support this. Thus, you must wrote your own shape layer class:Creating a layer with a transparent path:
I've used this code to draw a semi-transparent circle with transparent border in front of a green background:
Edit: Here is the corresponding code for the layer in Swift:
Note: By marking the properties with
@NSManaged
you can easily make the properties animatable by implementingneedsDisplay(forKey inKey:)
in Swift orneedsDisplayForKey:
in Objective C, respectively. I've adapted the Swift code accordingly.But even if you don't need animations, it is better to mark the properties with
@NSManaged
, because QuartzCore makes copies of layers and should also copy all properties with it.@NSManaged
in Swift is the counterpart to@dynamic
in Objective C, because it avoids the creation of a property implementation. InsteadCALayer
gets and sets property values withvalue(forKey:)
andsetValue(_:forKey:)
, respectively.