问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/5605618/core-animation-animation-doesnt-work