core-animationquartz-graphicscalayer

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


Solution

  • 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