CABasicAnimation CAAnimationGroup 对背景色做连续渐变动画

//此动画效果分三个阶段 程实原创

//1、从白色变为灰色
程实原创
//2、灰色变为橘色,再变为灰色,往返作三次 程实原创
//3、会后从灰色变为白色
程实原创

define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0fblue:(b)/255.0f alpha:1]

//此时做背景色渐变一定用CGColor

//要使用的三个颜色

CGColorRef originColor = [UIColor whiteColor].CGColor;
CGColorRef darkGray = RGBCOLOR(207, 205, 205).CGColor;
CGColorRef orange = RGBCOLOR(240, 221, 185).CGColor;

CGFloat
duration = 0.75
;

//1、从白色变为灰色
程实原创
CABasicAnimation *anim1 = [CABasicAnimationanimationWithKeyPath:@"backgroundColor"];
anim1.duration = duration;
anim1.fromValue = (id)originColor;
anim1.toValue = (id)darkGray;
//填充效果:动画结束后,动画将保持最后的表现状态

anim1.fillMode = kCAFillModeForwards;
anim1.removedOnCompletion = NO;
anim1.beginTime = 0.0f;

//下面介绍一下fillMode这个枚举

kCAFillModeRemoved 动画结束后,将会移除掉做的动画效果
kCAFillModeForwards 动画结束后,动画将保持最后的表现状态

kCAFillModeBackwards 与kCAFillModeForwards相对应
kCAFillModeBoth 是kCAFillModeForwards和kCAFillModeBackwards的结合
kCAFillModeFrozen 4.0之后就不推荐使用了。

CABasicAnimation *anim = [CABasicAnimationanimationWithKeyPath:@"backgroundColor"];
anim.duration = duration;
anim.fromValue = (id)darkGray;
anim.toValue = (id)orange;
anim.repeatCount = 3;
anim.autoreverses = YES;

//此时anim.removedOnCompletion和anim.fillMode设不设置都行。因为会被middleGroup的参数覆盖

anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeBoth;
anim.beginTime = 0.0f;

CAAnimationGroup * middleGroup = [CAAnimationGroup animation];

//一次动画用时duration,往返乘以2,做三次,用时*3,所以是6倍

middleGroup.duration = duration*6;
middleGroup.animations = @[anim];
middleGroup.removedOnCompletion = NO;

//此autoreverses设为yes则会坐动画还原

middleGroup.autoreverses = YES;
middleGroup.fillMode = kCAFillModeForwards;

//设置此动画的开始时间

middleGroup.beginTime = duration;

//变回原来颜色
CABasicAnimation *anim3 = [CABasicAnimationanimationWithKeyPath:@"backgroundColor"];
anim3.duration = duration;
anim3.fromValue = (id)darkGray;
anim3.toValue = (id)originColor;
anim3.removedOnCompletion = NO;
anim3.beginTime = duration * 7;
anim3.fillMode = kCAFillModeForwards;

CAAnimationGroup * theGroup = [CAAnimationGroup animation];
theGroup.duration = duration*8;
theGroup.animations = @[anim1,middleGroup,anim3];
theGroup.removedOnCompletion = NO;
theGroup.fillMode = kCAFillModeBoth;

[self.holderView.layer addAnimation:theGroup forKey:@"backgroundColor"];

你可能感兴趣的:(CABasicAnimation CAAnimationGroup 对背景色做连续渐变动画)