Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipping a CALayer to arbitrary path

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

like image 942
apchester Avatar asked Jul 20 '10 10:07

apchester


2 Answers

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
like image 168
Matt Long Avatar answered Oct 15 '22 08:10

Matt Long


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.

like image 23
Jorge OM Avatar answered Oct 15 '22 08:10

Jorge OM