2

How does one render a gradient inside a UIBezierPath and is it possible to store this state together with the bezierPath for faster re-rendering in drawRect?

I currently render bezierPaths inside drawRect but I cannot add a gradient.

When I call this method CGContextDrawLinearGradient (ctx, gradient, gradientStartPoint, gradientEndPoint, 0); I dont have an endPoint.

I tried using the BezierPath.currentPoint but I dont get the expected results.

some_id
  • 29,466
  • 62
  • 182
  • 304

1 Answers1

1

This wrapper function renders a gradient inside a UIBezierPath (Swift 4):

func drawLinearGradient(inside path:UIBezierPath, start:CGPoint, end:CGPoint, colors:[UIColor])
{
    guard let ctx = UIGraphicsGetCurrentContext() else { return }

    ctx.saveGState()
    path.addClip() // use the path as the clipping region

    let cgColors = colors.map({ $0.cgColor })
    guard let gradient = CGGradient(colorsSpace: nil, colors: cgColors as CFArray, locations: nil) 
        else { return }

    ctx.drawLinearGradient(gradient, start: start, end: end, options: [])

    ctx.restoreGState() // remove the clipping region for future draw operations
}

You could change this to render any type of gradient or other drawing code after you've set the clipping region using path.addClip().

And you could cache the CGGradient object to improve your chances of the graphics system speeding up future rendering passes.

Robin Stewart
  • 3,147
  • 20
  • 29