如何用渐变色填充贝塞尔path
我的自定义UIView draw(_ rect: CGRect)
函数中有一个UIBezierPath
。 我想用渐变色填充path。 请任何人都可以指导我如何做到这一点。
我需要用渐变颜色填充剪辑,然后用黑色描边path。
SO中有一些post不能解决问题。 例如沿着bezierpath的Swift:Gradient(使用CALayers)这篇文章指导了如何在UIView
绘制一个图层,但不是在UIBezierPath
。
注意:我正在Swift-3上工作
为了回答你的这个问题,
我的自定义UIView绘制(_ rect:CGRect)函数中有一个UIBezierPath。 我想用渐变色填充path。
比方说你有一条椭圆形的path,
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
要创build一个渐变,
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)
更新使用描边创build一个基础图层,并在创build渐变图层之前添加。
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)