【问题标题】:Fill circle border with gradient color using UIBezierPath使用 UIBezierPath 用渐变颜色填充圆形边框
【发布时间】:2018-07-07 19:40:32
【问题描述】:

我想使用带有渐变颜色的UIBazierpath 填充圆形边框的一半。

最初我尝试使用完整的圆圈,但它不起作用,渐变总是填充圆圈而不是边框​​。有没有办法做到这一点?

这是我目前所拥有的:

let path = UIBezierPath(roundedRect: rect, cornerRadius: rect.width/2)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 2.0
shape.strokeColor = UIColor.black.cgColor
self.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
shapeMask.lineWidth = 2

self.layer.addSublayer(gradient)

编辑:添加图像。我想实现这样的目标。

【问题讨论】:

  • 什么是“darwan”?目前还不清楚你的目标是什么。你有你想要的结果的图片吗?
  • 添加了图片。我看到了很多第三方代码,但这不是我要找的。​​span>
  • 核心图形渐变不直接支持这种渐变。这比使用渐变层或 CGGradient 需要更多的努力。

标签: swift gradient uibezierpath


【解决方案1】:

核心图形不支持轴向渐变,因此您需要以更手动的方式绘制出来。

这是一个自定义视图类,它使用圆周上的 HSV 颜色范围绘制一个圆。

class RadialCircleView: UIView {
    override func draw(_ rect: CGRect) {
        let thickness: CGFloat = 20
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = min(bounds.width, bounds.height) / 2 - thickness / 2
        var last: CGFloat = 0
        for a in 1...360 {
            let ang = CGFloat(a) / 180 * .pi
            let arc = UIBezierPath(arcCenter: center, radius: radius, startAngle: last, endAngle: ang, clockwise: true)
            arc.lineWidth = thickness
            last = ang
            UIColor(hue: CGFloat(a) / 360, saturation: 1, brightness: 1, alpha: 1).set()
            arc.stroke()
        }
    }
}

let radial = RadialCircleView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
radial.backgroundColor = UIColor(red: 0.98, green: 0.92, blue: 0.84, alpha: 1) // "antique white"

将其复制到 Playground 中以试验结果。颜色与您的图片不完全匹配,但可能满足您的需求。

【讨论】:

  • 太棒了。谢谢,这正是我一直在寻找:)