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)

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...