iPad: Animate UILabels color changing

后端 未结 7 408
礼貌的吻别
礼貌的吻别 2020-12-04 20:37

I have a label which pops up displaying points in my application. I am using the following code to make the label get larger in scale, then smaller. I would also like to ani

7条回答
  •  囚心锁ツ
    2020-12-04 20:59

    Unfortunately, the color doesn't animate with UIView animations. The answers to this question give some good workarounds without using Core Animation.

    If you don't mind using a CATextLayer instead of a UILabel, then the color (and the scaling in your example) can be animated like this:

    #import 
    //Also need to add QuartzCore framework to project (as well as the import).
    //
    -(void)animateTextLayer {
    
    CGFloat animationDuration = 5;
    
    CATextLayer *textLayer = [CATextLayer layer];
    [textLayer setString:@"Hello World"];
    [textLayer setForegroundColor:[UIColor purpleColor].CGColor];
    [textLayer setFontSize:30];
    [textLayer setFrame:CGRectMake(20, 200, 300, 40)];
    [[self.view layer] addSublayer:textLayer];
    
    CABasicAnimation *colorAnimation = [CABasicAnimation 
                                         animationWithKeyPath:@"foregroundColor"];
    colorAnimation.duration = animationDuration;
    colorAnimation.fillMode = kCAFillModeForwards;
    colorAnimation.removedOnCompletion = NO;
    colorAnimation.fromValue = (id)[UIColor purpleColor].CGColor;
    colorAnimation.toValue = (id)[UIColor greenColor].CGColor;
    colorAnimation.timingFunction = [CAMediaTimingFunction 
                                     functionWithName:kCAMediaTimingFunctionLinear];
    
    CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation 
                                            animationWithKeyPath:@"transform"];
    NSArray *scaleValues = [NSArray arrayWithObjects:
        [NSValue valueWithCATransform3D:CATransform3DScale(textLayer.transform, 1, 1, 1)],
        [NSValue valueWithCATransform3D:CATransform3DScale(textLayer.transform, 1.5, 1.5, 1)],
        [NSValue valueWithCATransform3D:CATransform3DScale(textLayer.transform, 0.5, 0.5, 1)], nil];
    [scaleAnimation setValues:scaleValues]; 
    scaleAnimation.fillMode = kCAFillModeForwards;
    scaleAnimation.removedOnCompletion = NO;
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.duration = animationDuration;
    animationGroup.timingFunction = [CAMediaTimingFunction 
                                    functionWithName:kCAMediaTimingFunctionLinear];
    animationGroup.fillMode = kCAFillModeForwards;
    animationGroup.removedOnCompletion = NO;
    animationGroup.animations = 
            [NSArray arrayWithObjects:colorAnimation, scaleAnimation, nil];
    
    [textLayer addAnimation:animationGroup forKey:@"animateColorAndScale"];
    }
    

提交回复
热议问题