some_id
some_id

Reputation: 29906

Rendering a gradient in a UIBezierPath

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.

Upvotes: 2

Views: 261

Answers (1)

Robin Stewart
Robin Stewart

Reputation: 3913

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.

Upvotes: 1

Related Questions