简体   繁体   中英

Core Animation - animation doesn't work

I'm attempting to use this code to animate a CALayer 's background color:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
animation.duration = 0.3;
animation.fromValue = (id)[backgroundLayer backgroundColor];
animation.toValue = (id)[[UIColor redColor] CGColor];
[backgroundLayer addAnimation:animation forKey:@"animateBackgroundColor"];

For some reason, this doesn't do anything. Simply using:

[backgroundLayer setBackgroundColor:[[UIColor redColor] CGColor]];

works (although without animation) and using:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration=0.3;
animation.fromValue = [NSNumber numberWithFloat:1.0];
animation.toValue = [NSNumber numberWithFloat:0.0];
[backgroundLayer addAnimation:animation forKey:@"animateOpacity"];

works, too (with animation).

Why can't I animate the background color?

EDIT: The problem is related to the fact that my backgroundColor is created with a pattern image (using UIImage 's implementation... Using solid colors works). I'm still looking for the answer to this problem.

Core Animation works by using interpolation--calculating intermediate values in between key values you specify. If it's a keyframe animation, it interpolates between the number (n) of values in your values array. If it's a basic animation, it interpolates between two values--your start and end values. CA can make the calculation just fine between two solid colors as these are just represented by RGBA float values, but how would it interpolate values between images? It would have to do some sort of morphing which I don't believe it is capable of. If you need a morphing effect, you are probably better off transitioning between background images in a view. The default effect there is a cross fade/dissolve effect. That may not be exactly what you're looking for, but it might get you pretty close.

Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM