How to fill a bezier path with gradient color

后端 未结 2 956
孤街浪徒
孤街浪徒 2020-12-30 07:29

I have a UIBezierPath inside my custom UIView draw(_ rect: CGRect) function. I would like to fill the path with a gradient color. Please can anybod

2条回答
  •  一个人的身影
    2020-12-30 07:49

    You can do this directly in Core Graphics without using CALayer classes. Use bezierPath.addClip() to set the bezier path as the clipping region. Any subsequent drawing commands will be masked to that region.

    I use this wrapper function in one of my projects:

    func drawLinearGradient(inside path:UIBezierPath, start:CGPoint, end:CGPoint, colors:[UIColor])
    {
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
    
        ctx.saveGState()
        defer { ctx.restoreGState() } // clean up graphics state changes when the method returns
    
        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: [])
    }
    

提交回复
热议问题