Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate Background Color Of UIButton from WhiteColor to RedColor

I'm trying to making a kind of color pulse effect animating background color of a UIButton to make it change continously from a color (WhiteColor) to another one (RedColor). I'm trying to use CABasicAnimation for changing Opacity but I can't make it work with color too.

    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"];

Every suggestion would be appreciated. Thanks

like image 410
pipizanzibar Avatar asked Feb 03 '15 14:02

pipizanzibar


2 Answers

I found the right way. You need to remember about CGColor. This was my mistake. Compiler didn't help here.

Objective 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"];

Swift

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")
like image 65
Dima Deplov Avatar answered Oct 28 '22 20:10

Dima Deplov


I finally found out solution: I made a two frames animation in which I first change background color to Red and in the second frame I turn it white. I can also manipulate relative durations

    [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];
like image 38
pipizanzibar Avatar answered Oct 28 '22 22:10

pipizanzibar