Swift - 使用animateWithDuration淡化CAGradientLayer

时间:2016-03-28 21:03:22

标签: ios swift fade cagradientlayer animatewithduration

我有switch语句控制我的背景渐变。它很好地工作(渐变变化),但它突然变化。我希望这些渐变能够以.25持续时间相互淡化。我的代码尝试在此处。

控制背景的切换语句:

switch backgroundInput{
case 50...69:
self.view.configureGradient([gradientColor1, gradientColor2])
case 70...90:
self.view.configureGradient([gradientColor2, gradientColor3])
case 91...110:
self.view.configureGradient([gradientColor3, gradientColor4])
case 111...130:
self.view.configureGradient([gradientColor4, gradientColor5])
case 131...150:
self.view.configureGradient([gradientColor5, gradientColor6])
case 151...170:
self.view.configureGradient([gradientColor6, gradientColor7])
default:
self.view.configureGradient([lightPurple, lightBlue])
}

控制渐变的扩展程序 这是我尝试动画持续时间的地方

extension UIView {
private func prepareGradient() -> CAGradientLayer {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.bounds
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
    gradientLayer.zPosition = -1
    self.layer.addSublayer(gradientLayer)
    return gradientLayer
}
func configureGradient(colors:[CGColor]) {
    let gradientLayer = prepareGradient()
    UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
        gradientLayer.colors = colors
        }, completion: nil)
}
}

如何调整上面的代码以使渐变层从一个渐变到另一个? (不相关 - 对于记忆而言,经常是不好的"在子图层上添加子层")

1 个答案:

答案 0 :(得分:2)

这将有效:

func configureGradient(colors:[CGColor]) {
    let gradientLayer = prepareGradient()
    gradientLayer.colors = colors
    UIView.transitionWithView(self,
                              duration: 0.25,
                              options: UIViewAnimationOptions.TransitionCrossDissolve,
                              animations: { [weak self] () -> Void in
                                self?.layer.addSublayer(gradientLayer)
        }, completion: nil)
}

...无论如何只添加子层来改变颜色并不酷。 尝试将渐变图层存储在扩展程序中:

private struct AssociatedKeys {
    static var gradientLayer = CAGradientLayer()
}

var gradientLayer: CAGradientLayer {
    get {
        guard let gLayer = objc_getAssociatedObject(self, &AssociatedKeys.gradientLayer) as? CAGradientLayer else { return CAGradientLayer() }
        return gLayer
    }
    set(value) {
        objc_setAssociatedObject(self, &AssociatedKeys.gradientLayer, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}

可能是一个UIView子类更容易实现......我认为你应该这样做。