I want to animate a UILabel to fade text in from left to right. My code below fades the entire UILabel in at once, but I would like to go letter by letter or word by word. Also, words can be added to this text, and when that happens I only want to fade in the new words, not the entire UILabel again.
__weak ViewController *weakSelf = self;
weakSelf.label.alpha = 0;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^{ weakSelf.label.alpha = 1;}
completion:nil];
I have done this once before with decent results. You will probably have to tweak it to your preference.
First step is to create a gradient image to match the way you want the text to fade in. If your text color is black you can try this.
- (UIImage *)labelTextGradientImage
{
CAGradientLayer *l = [CAGradientLayer layer];
l.frame = self.label.bounds;
l.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:0] CGColor], (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:1] CGColor], nil];
l.endPoint = CGPointMake(0.0, 0.0f);
l.startPoint = CGPointMake(1.0f, 0.0f);
UIGraphicsBeginImageContext(self.label.frame.size);
[l renderInContext:UIGraphicsGetCurrentContext()];
UIImage *textGradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return textGradientImage;
}
That code creates an black image that should fade from left to right.
Next, when you create you label, you need to set its text color based from a pattern made from the image we just generated.
self.label.alpha = 0;
self.label.textColor = [UIColor colorWithPatternImage:[self labelTextGradientImage]];
Assuming that works, the last step is to animate the label into view and change its text color while that happens.
[UIView transitionWithView:self.label duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
self.label.textColor = [UIColor blackColor];
self.label.alpha = 1;
} completion:^(BOOL finished) {
}];
The animation code is a little funky because the UILabel's textColor property doesn't seem to be animatable with a UIViewAnimation.
Well, I know how I would do it. I would make a mask containing a gradient, and animate the mask across the front of the label.
Here's the result when I do that (don't know whether it's exactly what you have in mind, but perhaps it's a start):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With