如何在 iOS swift 中更新运行时的 CAGradientLayer 颜色



我正在使用UIView扩展将梯度层应用于UIView。我需要在滚动表视图时在运行时更改渐变颜色。我使用滚动视图内容偏移值来更新渐变颜色。

我尝试过: 我尝试从超级图层中删除该图层,并使用新颜色创建一个新的渐变图层。但是应用程序遇到内存问题,并且 UI 有时会冻结。

是否可以在运行时更新CAGradientLayer渐变颜色?

extension UIView {
    func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.startPoint = orientation.startPoint
        gradient.endPoint = orientation.endPoint
        self.layer.insertSublayer(gradient, at: 0)
    }
}

这个问题的答案是从同一范围内更改渐变层的颜色属性。我以前尝试过这样做,但范围不同。现在它正在工作。答案如下。

Swift 3.1 代码:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
view.layer.insertSublayer(gradient, at: 0)
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { 
// this will be called after 10 seconds.
    gradient.colors = [UIColor.red.cgColor, UIColor.black.cgColor]
}

另一种解决方案是使用动画块来更改渐变颜色...

extension CAGradientLayer
{
    func animateChanges(to colors: [UIColor],
                        duration: TimeInterval)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock({
            // Set to final colors when animation ends
            self.colors = colors.map{ $0.cgColor }
        })
        let animation = CABasicAnimation(keyPath: "colors")
        animation.duration = duration
        animation.toValue = colors.map{ $0.cgColor }
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
        add(animation, forKey: "changeColors")
        CATransaction.commit()
    }
}

试试这个。希望它有帮助..

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
view.layer.insertSublayer(gradient, at: 0)

干杯

最新更新