Fade background-color from one color to another in a UIView
Asked Answered
C

1

5

How can I fade from one background-color to another color in a UIView?

In javascript (jQuery) it can be done by doing the following:
$('body').animate({ backgroundColor: "#ff00ff"});

Would it be easier if I converted the colors to HSV?

EDIT: Tried to do it with CABasicAnimation but it flashes white for unknown reasons. :/

CABasicAnimation* fade = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
fade.fillMode = kCAFillModeForwards;
fade.removedOnCompletion = NO;
// fade.fromValue = (id)[self.view backgroundColor].CGColor;
fade.toValue = (id)[UIColor greenColor].CGColor;
[self.view.layer addAnimation:fade forKey:@"fade"];

Then I tried to find another way to do it and stumbled upon "implicit animation". The following works with a nice fade of a second:

[UIView beginAnimations:@"fade" context:nil];
[UIView setAnimationDuration:1];
[[self view] setBackgroundColor: [UIColor greenColor]];
[UIView commitAnimations];

Thanks, StackOverflow, for helping everyone learn even more. :)

Chambless answered 24/1, 2011 at 17:29 Comment(1)
Duplicate: #518692Gorizia
A
1

You don't need to create two UIView and fade - why bother having an extra superfluous view hanging around when the color attribute itself is animatable?

You can use CAAnimation as shown above, but instead of adjusting the opacity of two views just adjust the backgroundColor of one.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Animation_Types_Timing/Articles/PropertyAnimations.html

Aedes answered 24/1, 2011 at 17:44 Comment(1)
I was trying to say that I have one UIView. I'll check your link. :)Chambless

© 2022 - 2024 — McMap. All rights reserved.