在iOS App中使用CoreAnimation/QuartzCore动画UILabel

Dev*_*rak 7 xcode cocoa-touch core-animation ios quartz-core

我实际上在我的iOS应用程序中设置了动画UILabel的问题.在网络上搜索代码片段2天后,仍然没有结果.

我找到的每个样本都是关于如何为UIImage制作动画,将其作为子视图添加到UIView中.有没有关于动画UILabel的好例子?我通过设置alpha属性为闪烁动画找到了一个很好的解决方案,如下所示:

我的功能:

- (void)blinkAnimation:(NSString *)animationID finished:(BOOL)finished target:(UIView *)target
{
    NSString *selectedSpeed = [[NSUserDefaults standardUserDefaults] stringForKey:@"EffectSpeed"];
    float speedFloat = (1.00 - [selectedSpeed floatValue]);

    [UIView beginAnimations:animationID context:target];
    [UIView setAnimationDuration:speedFloat];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(blinkAnimation:finished:target:)];

    if([target alpha] == 1.0f)
        [target setAlpha:0.0f];
    else
        [target setAlpha:1.0f];
    [UIView commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)

在UILabel上调用我的函数:

[self blinkAnimation:@"blinkAnimation" finished:YES target:labelView];
Run Code Online (Sandbox Code Playgroud)

但是Pulse或缩放动画怎么样?

sgr*_*454 13

不幸的是,字体大小不是NSView的可动画属性.为了扩展UILabel,您需要使用更高级的Core Animation技术,使用CAKeyframeAnimation:

  1. 将QuartzCore.framework导入项目和#import <QuartzCore/QuartzCore.h>代码中.
  2. 创建一个可以添加关键帧的新CAKeyframeAnimation对象.
  3. 创建一个定义缩放操作的CATransform3D值(不要被3D部分混淆 - 您使用此对象对图层进行任何变换).
  4. 通过使用其方法将转换添加到CAKeyframeAnimation对象,使转换成为动画中的关键帧之一setValues.
  5. 通过调用其setDuration方法设置动画的持续时间
  6. 最后,使用[[yourLabelObject layer] addAnimation:yourCAKeyframeAnimationObject forKey:@"anyArbitraryString"] 将动画添加到标签的图层

最终的代码看起来像这样:

// Create the keyframe animation object
CAKeyframeAnimation *scaleAnimation = 
   [CAKeyframeAnimation animationWithKeyPath:@"transform"];

// Set the animation's delegate to self so that we can add callbacks if we want
scaleAnimation.delegate = self;

// Create the transform; we'll scale x and y by 1.5, leaving z alone 
// since this is a 2D animation.
CATransform3D transform = CATransform3DMakeScale(1.5, 1.5, 1); // Scale in x and y

// Add the keyframes.  Note we have to start and end with CATransformIdentity, 
// so that the label starts from and returns to its non-transformed state.
[scaleAnimation setValues:[NSArray arrayWithObjects:
                  [NSValue valueWithCATransform3D:CATransform3DIdentity],
                  [NSValue valueWithCATransform3D:transform],
                  [NSValue valueWithCATransform3D:CATransform3DIdentity],
                  nil]];

// set the duration of the animation
[scaleAnimation setDuration: .5];

// animate your label layer = rock and roll!
[[self.label layer] addAnimation:scaleAnimation forKey:@"scaleText"];
Run Code Online (Sandbox Code Playgroud)

我将把重复的"脉冲"动画作为练习留给你:暗示,它涉及到animationDidStop方法!

另外一个注意事项 - 可以在此处找到CALayer可动画属性的完整列表(其中"transform"为1).快乐的补间!