这个包装函数在 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
}
在使用path.addClip()
.
并且您可以缓存CGGradient
对象以提高图形系统加速未来渲染通道的机会。