【问题标题】:How to update CAGradientLayer colors on runtime in iOS swift?如何在 iOS swift 运行时更新 CAGradientLayer 颜色?
【发布时间】:2017-05-24 10:51:40
【问题描述】:

我正在使用 UIView 扩展将渐变层应用到 UIView。我需要在滚动表视图时在运行时更改渐变颜色。我使用滚动视图的 contentoffset 值来更新渐变颜色。

我尝试了什么: 我试图从超级图层中删除图层并使用新颜色创建一个新的渐变图层。但应用程序出现内存问题,用户界面有时会冻结。

是否可以在运行时更新 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)
    }
}

【问题讨论】:

  • 将渐变层保留在一个属性中并更新其颜色属性。
  • 是的。它似乎在工作@Alistra。谢谢

标签: ios swift animation uiview cagradientlayer


【解决方案1】:

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

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]
}

【讨论】:

    【解决方案2】:

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

    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()
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个。希望对您有所帮助..

      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)
      

      干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多