10

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

apchester
  • 1,154
  • 3
  • 11
  • 30

2 Answers2

15

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
Wyetro
  • 8,439
  • 9
  • 46
  • 64
Matt Long
  • 24,438
  • 4
  • 73
  • 99
1

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.

Jorge OM
  • 79
  • 7