我用switch语句控制背景渐变。它很好地工作(渐变变化),但它突然变化。我希望这些渐变以0.25的持续时间彼此淡入。我的代码尝试如下。
控制背景的Switch语句:
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)
}
}
如何调整上面的代码以使渐变层从一个渐变到另一个?(不相关-内存在子层上不断地“添加子层”是否有害?)
最佳答案
这将起作用:
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子类更容易实现。。。我认为你应该这样做。
关于ios - Swift-使用animateWithDuration淡出CAGradientLayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36271146/