用渐变笔画绘制一个圆

时间:2017-08-13 17:34:44

标签: ios swift core-graphics cagradientlayer

我正在开展一项任务,我必须创建一个没有填充但是渐变笔划的圆。作为参考,这是我追求的最终结果;

Circle with gradient stroke

鉴于应用程序的其他事件,我正在绘制我的圈子;

let c = UIGraphicsGetCurrentContext()!
c.saveGState()
let clipPath: CGPath = UIBezierPath(roundedRect: converted_rect, cornerRadius: converted_rect.width / 2).cgPath
c.addPath(clipPath)
c.setLineWidth(9.0)
c.setStrokeColor(UIColor.blue.cgColor)
c.closePath()
c.strokePath()
c.restoreGState()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

这会产生一个蓝色笔划的圆圈。尽管在SO周围进行了很多搜索,但我仍在努力弄清楚如何用渐变而不是蓝色替换setStrokeColor。我最大的成功来自于创建CAGradientLayer,然后使用从路径创建的CAShapeLayer屏蔽它,但我只能创建一个实心圆而不是空心圆。

谢谢!

1 个答案:

答案 0 :(得分:6)

基本思路是将路径用作剪切路径,然后绘制渐变。

{% include %}

首先使用所需的颜色设置let c = UIGraphicsGetCurrentContext()! let clipPath: CGPath = UIBezierPath(ovalIn: converted_rect).cgPath c.saveGState() c.setLineWidth(9.0) c.addPath(clipPath) c.replacePathWithStrokedPath() c.clip() // Draw gradient let colors = [UIColor.blue.cgColor, UIColor.red.cgColor] let offsets = [ CGFloat(0.0), CGFloat(1.0) ] let grad = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: offsets) let start = converted_rect.origin let end = CGPoint(x: converted_rect.maxX, y: converted_rect.maxY) c.drawLinearGradient(grad!, start: start, end: end, options: []) c.restoreGState() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() 。然后,对于线性渐变,使用CGGradient。对于径向渐变,请使用drawLinearGradient