Is it possible to clip a CALayer to an arbitrary path? I am aware that I can clip to the superlayer's bounds, but in this case I need to be far more prescriptive.
TIA, Adam
Use a CAShapeLayer as the mask for the layer you want to clip. CAShapeLayer has a path property that takes a CGPathRef.
For example:
let mask = CAShapeLayer()
mask.path = path // Where path is some CGPath
layer.mask = mask // Where layer is your CALayer
// This also works for other CAShapeLayers
Yes you can override the drawInContext of you custom layer.
func addPathAndClipIfNeeded(ctx:CGContext) {
if (self.path != nil) {
CGContextAddPath(ctx,self.path);
if (self.stroke) {
CGContextSetLineWidth(ctx, self.lineWidth);
CGContextReplacePathWithStrokedPath(ctx);
}
CGContextClip(ctx);
}
}
override public func drawInContext(ctx: CGContext) {
super.drawInContext(ctx)
addPathAndClipIfNeeded(ctx)
}
Or you can create a CAShapeLayer as mask.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With