UIBezierPath with color gradient

前端 未结 5 1669
孤街浪徒
孤街浪徒 2021-02-08 15:21

I\'ve got an question about UIBezierPath.

For example I\'ve got this path:

\"\"

Now I want to have

5条回答
  •  庸人自扰
    2021-02-08 15:50

    Another take on Oleg's answer regarding the saturation (white gradient) that I find more pleasing, and in Swift (3).

    You can add steps to the gradient if you want a bigger white circle (ex a 2nd white step at 0.2)

    import UIKit
    
    class HSView: UIView {
        override func draw(_ rect: CGRect) {
            let arcStep = 2 * CGFloat.pi / 360
            let isClockwise = false
            let x = rect.width / 2
            let y = rect.height / 2
            let radius = min(x, y) / 2
            let ctx = UIGraphicsGetCurrentContext()
            ctx?.setLineWidth(2 * radius)
    
            for i in 0..<360 {
                let color = UIColor(hue: CGFloat(i)/360, saturation: 1, brightness: 1, alpha: 1)
                let startAngle = CGFloat(i) * arcStep
                let endAngle = startAngle + arcStep + 0.02
    
                ctx?.setStrokeColor(color.cgColor)
                ctx?.addArc(center: CGPoint(x: x, y: y), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: isClockwise)
                ctx?.strokePath()
            }
    
            let gradient = CGGradient(colorsSpace: UIColor.white.cgColor.colorSpace,
                                      colors: [
                                        UIColor.white.cgColor,
                                        UIColor.white.withAlphaComponent(0).cgColor,
                                        ] as CFArray,
                                      locations: [
                                        0,
                                        1,
                ]
            )
            ctx?.drawRadialGradient(gradient!, startCenter: CGPoint(x: x, y: y), startRadius: 0, endCenter: CGPoint(x: x, y: y), endRadius: 2 * radius, options: .drawsAfterEndLocation)
        }
    }
    

提交回复
热议问题