Swift贝塞尔曲线填充渐变填充

Swift bezier curve fill gradient fill

尝试在 Swift 中使用 CG 绘图在我的情节提要中的视图上创建此曲线。 我已经完成了白色曲线,但无法用图中所示的渐变填充它

这张图片分为三部分。

  1. 白色曲线。
  2. 渐变。
  3. 屏蔽渐变的蒙版。

最好的方法是将它们创建为单独的图层。

首先用你想要的颜色创建一个CAGradientLayer。 然后创建一条白色的路径曲线并将其添加到渐变上方。

现在创建具有封闭路径的第三层(类似于曲线但在底部封闭。将其用作渐变层上的 maskLayer。

这是工作代码

class FillCurve: UIView {


    override func draw(_ rect: CGRect) {
        // Drawing ARC

        let center = CGPoint(x: bounds.width /  2 , y: bounds.height / 2)
        let curve = UIBezierPath()
        curve.move(to:CGPoint(x: 10, y: bounds.height - 20))
        curve.addQuadCurve(to: CGPoint(x: bounds.width - 20 , y: bounds.height - 20), controlPoint:center )
        UIColor.white.setStroke()
        curve.lineWidth = 2.0

        curve.stroke()

        let fillPath = curve.copy() as! UIBezierPath

        fillPath.addLine(to: CGPoint(x: bounds.width , y: bounds.height - 2))
        fillPath.addLine(to: CGPoint(x: 0, y: bounds.height - 2))

        fillPath.close()
        fillPath.fill()
        fillPath.addClip()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let colors = [UIColor.cyan.cgColor,UIColor.black.cgColor]
        let location:[CGFloat] = [0.0,1.0]
        let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: location)!
        UIGraphicsGetCurrentContext()?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: fillPath.bounds.height), end: CGPoint(x: 0, y: bounds.height), options: [])

    }


}

输出