dickfala
dickfala

Reputation: 3306

iOS the CABasicAnimation color animation not effect

I am implement the the color animation.

I want to black color change to gradient color.

I search some method, that can use the CAGradientLayer to define the gradient color, and the CABasicAnimation can achieve the color change animation.

But I implement below the code, the self view not change to the black in the first, and the color was not animation .

Have anyone know what happened for these code?

thank you very much.

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

Upvotes: 1

Views: 1360

Answers (1)

Robert Gummesson
Robert Gummesson

Reputation: 5666

Here is what you need to do. Cleaned up your code a little bit too. :)

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

Upvotes: 2

Related Questions