I'm having trouble trying to get a custom UIView class to fade it's background. I've checked out the following StackOverflow questions but they don't seem to work for me.
Fade background-color from one color to another in a UIView
How do you explicitly animate a CALayer's backgroundColor?
So I have a custom UIView where users can draw things. If what they draw is incorrect, I want to make the background color fade to red then back to white.
I have this custom method in the custom UIView called
- (void)indicateMistake;
When I call that method I want it to perform the background color animation, so i have this in the method:
CABasicAnimation* fade = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
fade.fromValue = (id)[UIColor whiteColor].CGColor;
fade.toValue = (id)[UIColor redColor].CGColor;
[fade setDuration:3];
[self.layer addAnimation:fade forKey:@"fadeAnimation"];
But nothing seems to happen when I do that.
So then I tried a silly rotation animation to see if it even works:
CABasicAnimation* rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotate.toValue = [NSNumber numberWithInt:M_PI];
[rotate setDuration:1];
[self.layer addAnimation:rotate forKey:@"rotateAnimation"];
For some reason that works and the custom UIView rotates.
Then reading more StackOverflow answers I tried this:
[UIView animateWithDuration:3 animations:^{
[self setBackgroundColor: [UIColor redColor]];
} completion:^(BOOL finished) {
[self setBackgroundColor: [UIColor whiteColor]];
}];
That changes the color from red then back to white immediately. Sometimes It's so fast I sometimes can't see it happen. If i comment out the [self setBackgroundColor: [UIColor whiteColor]];
it stays red. But There's node gradual white to red effect.
I've ran out of ideas.. Any help would be appreciated!
So I have a custom UIView where users can draw things.
I'm assuming that means you've implemented -drawRect:
.
IIRC, by default (if UIView.clearsContextBeforeDrawing
is set), the context gets filled with the view's background colour, -drawRect:
gets called, and the resulting bitmap is drawn on screen instead of the background colour. Animating this would mean animating between the two bitmaps, which isn't something Core Animation is particularly good at. (I could be wrong about the details here, but it explains the behaviour).
The easiest fix is to set the background colour to [UIColor clearColor]
and animate the background colour of a view behind the one you are drawing to. This means the view will not need to be redrawn, only recomposited over the "background".