从WhiteColor到RedColor的UIButton背景颜色动画

pip*_*bar 5 objective-c uibutton cabasicanimation ios

我正在尝试制作一种颜色脉冲效果,使a的背景颜色动画UIButton,使其从颜色(WhiteColor)连续变化到另一种颜色(RedColor).我正在尝试CABasicAnimation用于改变不透明度,但我也无法使用颜色.

    CABasicAnimation *theAnimation;

    theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    theAnimation.duration=1.0;
    theAnimation.repeatCount=HUGE_VALF;
    theAnimation.autoreverses=YES;
    theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
    theAnimation.toValue=[NSNumber numberWithFloat:0.0];
    [BigButton.layer addAnimation:theAnimation forKey:@"animateOpacity"];
Run Code Online (Sandbox Code Playgroud)

我们将不胜感激.谢谢

Dim*_*lov 5

我找到了正确的方法.你需要记住CGColor.这是我的错.编译器在这里没有帮助.

目标C.

CABasicAnimation *theAnimation=[CABasicAnimation animationWithKeyPath:@"backgroundColor"];
theAnimation.duration=1.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;
theAnimation.fromValue= [[UIColor redColor] CGColor];
theAnimation.toValue= [[UIColor blueColor] CGColor];
[BigButton.layer addAnimation:theAnimation forKey:@"ColorPulse"];
Run Code Online (Sandbox Code Playgroud)

迅速

let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.fromValue = UIColor.redColor().CGColor
colorAnimation.toValue = UIColor.blueColor().CGColor
colorAnimation.duration = 1
colorAnimation.autoreverses = true
colorAnimation.repeatCount = FLT_MAX
self.layer.addAnimation(colorAnimation, forKey: "ColorPulse")
Run Code Online (Sandbox Code Playgroud)


pip*_*bar 3

我终于找到了解决方案:我制作了一个两帧动画,其中我首先将背景颜色更改为红色,然后在第二帧中将其变为白色。我还可以操纵相对持续时间

    [UIView animateKeyframesWithDuration:2.0 delay:0.0 options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat animations:^{
        [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor redColor];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
            someView.backgroundColor = [UIColor whiteColor];
        }];
    } completion:nil];
Run Code Online (Sandbox Code Playgroud)