Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading UILabel in from left to right

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];
like image 952
stevenA Avatar asked Feb 10 '23 02:02

stevenA


2 Answers

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.

like image 105
Dare Avatar answered Feb 13 '23 15:02

Dare


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):

enter image description here

like image 44
matt Avatar answered Feb 13 '23 14:02

matt