简体   繁体   English

动画CALayer背景颜色并更新模型值

[英]Animating CALayer background color and update model value

I want to animate a backgroundColor change for a sublayer in my UIView (on tintColorDidChange ). 我想为我的UIView中的子图层设置backgroundColor更改动画(在tintColorDidChange )。

I need to animate from the layer's current background colour to the new tint colour several times (different tint colours each time), so the model value for backgroundColor needs to be updated (I can't use removedOnCompletion = false on the animation). 我需要多次从图层的当前背景颜色动画到新的色调颜色(每次都有不同的色调颜色),因此需要更新backgroundColor的模型值(我不能在动画上使用removedOnCompletion = false )。

Using CABasicAnimation I have the colour change animation working fine if I don't update the model value (but of course the colour resets after the animation is complete). 使用CABasicAnimation如果我不更新模型值,我可以正常使用颜色更改动画(当然,在动画完成后颜色会重置)。 When I try to update the model value the colour change happens immediately and the animation is lost. 当我尝试更新模型值时,颜色更改立即发生,动画丢失。

I attempted to disable the implicit animation and update the model value with CATransation but the animation is still lost. 我尝试禁用隐式动画并使用CATransation更新模型值,但动画仍然丢失。

How can I update the backgroundColor model value and keep my fade animation working? 如何更新backgroundColor模型值并使我的淡入淡出动画保持有效?

override func tintColorDidChange() {
    super.tintColorDidChange()

    let colourAnim = CABasicAnimation(keyPath: "backgroundColor")
    colourAnim.toValue = self.tintColor.CGColor
    colourAnim.duration = 1.0
    self.spinnerLayer?.addAnimation(colourAnim, forKey: "colourAnimation")

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    self.spinnerLayer?.backgroundColor = self.tintColor.CGColor
    CATransaction.commit()
}

Use an explicit fromValue for the animation: 对动画使用显式的fromValue

override func tintColorDidChange() {
    super.tintColorDidChange()

    let colourAnim = CABasicAnimation(keyPath: "backgroundColor")
    colourAnim.fromValue = self.spinnerLayer!.backgroundColor
    colourAnim.toValue = self.tintColor.CGColor
    colourAnim.duration = 1.0
    self.spinnerLayer?.addAnimation(colourAnim, forKey: "colourAnimation")
    self.spinnerLayer?.backgroundColor = self.tintColor.CGColor

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM