如何用渐变颜色填充贝塞尔曲线路径

How to fill a bezier path with gradient color

我的自定义 UIView draw(_ rect: CGRect) 函数中有一个 UIBezierPath。我想用渐变颜色填充路径。请任何人指导我该怎么做。

我需要用渐变颜色填充剪辑,然后用黑色描边路径。

SO中有一些post没有解决问题。例如 Swift: Gradient along a bezier path (using CALayers) 这个 post 指导如何在 UIView 中而不是 UIBezierPath 中的图层上绘制。

注意:我正在研究 Swift-3

为了回答你的这个问题,

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

假设您有一条椭圆形路径,

let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))

要创建渐变,

let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]

我们需要一个渐变遮罩层,

let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath

现在将此 shapeLayer 设置为 gradient 层的 mask 并将其添加到 view 的层作为 subLayer

gradient.mask = shapeMask
yourCustomView.layer.addSublayer(gradient)

更新 创建一个带有描边的基础层,在创建渐变层之前添加。

let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 2.0
shape.strokeColor = UIColor.black.cgColor
self.view.layer.addSublayer(shape)

let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]

let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath
gradient.mask = shapeMask

self.view.layer.addSublayer(gradient)

您可以直接在 Core Graphics 中执行此操作,而无需使用 CALayer 类。使用 bezierPath.addClip() 将贝塞尔曲线路径设置为裁剪区域。任何后续绘图命令都将被屏蔽到该区域。

我在我的一个项目中使用了这个包装函数:

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({ [=10=].cgColor })
    guard let gradient = CGGradient(colorsSpace: nil, colors: cgColors as CFArray, locations: nil)
        else { return }

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