Clip Drawing to Opaque (Stroke) Part of CAShapeLayer

444 views Asked by At

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.

3

There are 3 answers

0
Connor Neville On BEST ANSWER

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()
1
Duncan C On

What if you add your shape layer as the mask of your gradient layer? That should work, since that's what a mask layer is supposed to do.

If that doesn't work you might need to capture your shape layer to an image and install THAT as the mask of your gradient layer.

0
matt On

Convert the stroked path to a new path whose fill area is the same as the original stroke. Now you have a fillable area that you can use as clipping area. The CGContext way to do this is by calling replacePathWithStrokedPath. As the docs explicitly say:

For example, you can clip to the stroked version of a path by calling this function followed by a call to the function clip().