使用带有径向渐变的 CAGradientLayer 时出现奇怪的渐变。

Weird gradient when using CAGradientLayer with radial gradient.

使用代码:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let v = View()
        view.addSubview(v)
        v.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
    }
}

class View : UIView {
    let gradientLayer = CAGradientLayer()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .blue

        gradientLayer.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.type = .radial
        gradientLayer.colors = [
            UIColor.red.cgColor,
            UIColor.green.cgColor
        ]
        self.layer.addSublayer(gradientLayer)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

期望(由 Sketch 生成):

iOS 12 模拟器上的代码结果:

真实 iOS 设备上的代码结果:

我的Xcode版本是10.0(10A255),我发现这个问题只有在 startPoint.x == endPoint.x || startPoint.y == endPoint.y

当startPoint和endPoint的y相等时,渐变椭圆的高度为0

在您的代码片段中,您可以将entPoint的y设置为1来实现Sketch效果。

在QuartzCore框架中,有如下注释:

/* Radial gradient. The gradient is defined as an ellipse with its * center at 'startPoint' and its width and height defined by * '(endPoint.x - startPoint.x) * 2' and '(endPoint.y - startPoint.y) * * 2' respectively. */

@available(iOS 3.2, *)

public static let radial: CAGradientLayerType