如何使用颜色渐变笔划绘制圆形路径 [英] How to draw a circle path with color gradient stroke

查看:238
本文介绍了如何使用颜色渐变笔划绘制圆形路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iOS和macOS上绘制一个带有颜色渐变笔画的圆圈,如下图所示:

I want to draw a circle with color gradient stroke like the following picture, on both iOS and macOS:

是否可以用 CAShapeLayer NSBezierPath / <实现code> CGPath ?还是其他任何方式?

Is it possible to implement with CAShapeLayer or NSBezierPath/CGPath? Or any other ways?

推荐答案

不是真的,但你可以用不同的颜色划一系列弧线:

Not really, but you can just stroke a series of arcs in different colors:

import Cocoa

/// This draws an arc, of length `maxAngle`, ending at `endAngle. This is `@IBDesignable`, so if you
/// put this in a separate framework target, you can use this class in Interface Builder. The only
/// property that is not `@IBInspectable` is the `lineCapStyle` (as IB doesn't know how to show that).
///
/// If you want to make this animated, just use a `CADisplayLink` update the `endAngle` property (and
/// this will automatically re-render itself whenever you change that property).

@IBDesignable class GradientArcView: NSView {

    /// Width of the stroke.

    @IBInspectable var lineWidth: CGFloat = CGFloat(3)          { didSet { setNeedsDisplay(bounds) } }

    /// Color of the stroke (at full alpha, at the end).

    @IBInspectable var strokeColor: NSColor = NSColor.blue      { didSet { setNeedsDisplay(bounds) } }

    /// Where the arc should end, measured in degrees, where 0 = "3 o'clock".

    @IBInspectable var endAngle: CGFloat = 0                    { didSet { setNeedsDisplay(bounds) } }

    /// What is the full angle of the arc, measured in degrees, e.g. 180 = half way around, 360 = all the way around, etc.

    @IBInspectable var maxAngle: CGFloat = 360                  { didSet { setNeedsDisplay(bounds) } }

    /// What is the shape at the end of the arc.

    var lineCapStyle: NSLineCapStyle = .squareLineCapStyle      { didSet { setNeedsDisplay(bounds) } }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        let gradations = 255

        let startAngle = -endAngle + maxAngle
        let center = NSPoint(x: bounds.origin.x + bounds.size.width / 2, y: bounds.origin.y + bounds.size.height / 2)
        let radius = (min(bounds.size.width, bounds.size.height) - lineWidth) / 2
        var angle = startAngle

        for i in 1 ... gradations {
            let percent = CGFloat(i) / CGFloat(gradations)
            let endAngle = startAngle - percent * maxAngle
            let path = NSBezierPath()
            path.lineWidth = lineWidth
            path.lineCapStyle = lineCapStyle
            path.appendArc(withCenter: center, radius: radius, startAngle: angle, endAngle: endAngle, clockwise: true)
            strokeColor.withAlphaComponent(percent).setStroke()
            path.stroke()
            angle = endAngle
        }

    }

}

这篇关于如何使用颜色渐变笔划绘制圆形路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆