动画UIButton的背景颜色从白色到红色

时间:2015-02-03 14:32:44

标签: ios objective-c uibutton cabasicanimation

我试图制作一种颜色脉冲效果,使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"];

我们将不胜感激。 感谢

3 个答案:

答案 0 :(得分: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"];

夫特

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")

答案 1 :(得分: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];

答案 2 :(得分:0)

Swift 4 - 对按钮(static navigationOptions = ({ navigation }) => ({ header: props => <Header navigation={navigation} title={'Dashboard'} toggleDrawer /> }) backgroundColortitle)的任何更改进行动画处理:

titleColor