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

我的自定义UIView绘图(_ rect:CGRect)函数中有一个UIBezierPath.我想用渐变色填充路径.请任何人都可以指导我如何做到这一点.

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

SO中有一些帖子无法解决问题.例如Swift: Gradient along a bezier path (using CALayers)这篇文章指导如何在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设置为渐变图层的蒙版,并将其作为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)

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...