0
votes

My CGContext has a path and a line width, this draws a nice black outline of my path in my UIView. Great. Now I’m trying to colour this stroke, and although the CGContextSetStrokeColorWithColor method isn’t bad, I want a more vibrant colour so decided to use a gradient.

The problem is there’s no CGContextSetStrokeColorWithGradient method in iOS or (that I can see) anything similar. So I figured I must be able to draw a gradient which is clipped to the stroke I’ve drawn.

To do that, I’ve drawn my gradient to my UIView and now the UIView has a gradient background which fills the view.

So now I have a black stroke and my gradient. Great. But how do I clip one to the other? So it looks like my stroke has the colour of the gradient?

I’ve called CGContextClip between creating the stroke and the gradient, but this doesn’t clip the gradient to the stroke, it just clips the gradient to the fill of the path. The only thing I want to clip the gradient to is the stroke.

Any ideas?

Here’s my drawRect:

let context = UIGraphicsGetCurrentContext()
let colourSpace = CGColorSpaceCreateDeviceRGB()

let path = CGPathCreateMutableCopy(path())

CGContextSetLineWidth(context, myLineWidth)
CGContextSetLineCap(context, kCGLineCapRound)
CGContextAddPath(context, path)

CGContextClip(context)

CGContextStrokePath(context)

let gradient = CGGradientCreateWithColors(colourSpace,
    [startColour.CGColor, endColour.CGColor],
    [0.0, 1.0])

CGContextDrawLinearGradient(context,
    gradient,
    CGPoint.zeroPoint,
    CGPoint(x: 0, y: bounds.height),
    CGGradientDrawingOptions.allZeros)
1

1 Answers

1
votes

So the simple CGContextReplacePathWithStrokedPath method is what I needed. Docs could be a bit clearer as to state what is being sent to the context, but there we go...