我的自定义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)