iOS CABasicAnimation 彩色动画没有效果

iOS the CABasicAnimation color animation not effect

我正在实现彩色动画。

我想把黑色改成渐变色

我搜索了一些方法,可以使用CAGradientLayer定义渐变颜色,CABasicAnimation可以实现颜色变化动画。

但是我在代码下面实现,一开始self view没有变黑,颜色也不是动画。

有人知道这些代码发生了什么吗?

非常感谢。

 // set black color in the view
CALayer *orginLayer = [CALayer layer];
orginLayer.backgroundColor = [[UIColor blackColor] CGColor];
[self.view.layer addSublayer:orginLayer];


// set gradient layer
CAGradientLayer  *colorLayer = [ CAGradientLayer layer];
colorLayer.frame     = ( CGRect ){ CGPointZero , CGSizeMake ( self.view.frame.size.width   , self.view.frame.size.height )};
colorLayer.position = self .view.center;

// define colors
UIColor *color1 = [UIColor colorWithRed:(255/255.0) green:(137/255.0) blue:(0/255.0) alpha:1.0];
UIColor *color2 = [UIColor colorWithRed:(247/255.0) green:(241/255.0) blue:(107/255.0) alpha:1.0];

NSArray *colors = [NSArray arrayWithObjects:(id)color1.CGColor,color2.CGColor,nil];
colorLayer.colors = colors;
colorLayer.startPoint = CGPointMake ( 1 , 0 );
colorLayer.endPoint = CGPointMake ( .3, 1 );

// set the color animation black color-> gradient color
CABasicAnimation *animation;
animation = [CABasicAnimation animationWithKeyPath:@"colors"];
[animation setToValue:colorLayer];
[animation setDuration:10];
[animation setRemovedOnCompletion:YES];
[animation setFillMode:kCAFillModeForwards];
[animation setDelegate:self];
[self.view.layer addAnimation:animation forKey:@"animateGradient"];

这是您需要做的。也稍微清理了你的代码。 :)

// set gradient layer
CAGradientLayer *colorLayer = [CAGradientLayer layer];
colorLayer.frame = (CGRect){ { }, self.view.frame.size };
colorLayer.position = self.view.center;

// define colors
UIColor *color1 = [UIColor colorWithRed:255/255. green:137/255. blue:0/255. alpha:1.0];
UIColor *color2 = [UIColor colorWithRed:247/255. green:241/255. blue:107/255. alpha:1.0];

NSArray *colors = @[(id)color1.CGColor, (id)color2.CGColor];
colorLayer.colors = colors;
colorLayer.startPoint = CGPointMake(1, 0);
colorLayer.endPoint = CGPointMake(.3, 1);

// set the color animation black color-> gradient color
CABasicAnimation *animation;
animation = [CABasicAnimation animationWithKeyPath:@"colors"];
animation.fromValue = @[(id)[UIColor blackColor].CGColor, (id)[UIColor blackColor].CGColor];
animation.toValue = colors;
animation.duration = 10;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
[colorLayer addAnimation:animation forKey:@"animateGradient"];
[self.view.layer addSublayer:colorLayer];