Search code examples
iosswiftcore-graphicsquartz-core

Clip Drawing to Opaque (Stroke) Part of CAShapeLayer


I have a CAShapeLayer with an opaque stroke and a transparent fill. I then want to call myContext.drawRadialGradient, but have this radial gradient clip to the stroke of my shape layer. Currently, I'm calling myShapeLayer.path.addClip(), which clips the radial gradient to the fill region of the shape layer, instead of the stroke.

In other words, I'd like to use either just the opaque part of a layer or just the stroke (same thing in my case), and use it to clip the current context. I've been searching the CoreGraphics docs for a while to no avail.


Solution

  • Found my answer. You can create a new UIBezierPath that is a copy of your existing one, with a stroke, as below:

    let strokePath = UIBezierPath(cgPath: oldPath.cgPath.copy(
        strokingWithWidth: ..., lineCap: ..., lineJoin: ..., miterLimit: ...))
    strokePath.addClip()