使用 UIBezierPath 用渐变色填充圆形边框

Fill circle border with gradient color using UIBezierPath

我想使用 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)

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

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

这是一个自定义视图 class,它使用围绕圆周的 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 中以试验结果。颜色与您的图片不完全匹配,但它可能会满足您的需求。