2011-09-21 27 views
7

實際上,我在iOS應用程序中動畫UILabel時遇到了問題。 在網絡搜索代碼片段2天后,仍然沒有結果。在iOS應用程序中使用Corelnimation/QuartzCore動畫UILabel

我發現的每個示例都是關於如何對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]; 
} 

叫我的功能上的UILabel:

[self blinkAnimation:@"blinkAnimation" finished:YES target:labelView]; 

但如何一個脈衝,或縮放動畫?

回答

13

不幸的是,字體大小不是NSView的動畫屬性。爲了擴展一個UILabel,你需要使用更先進的Core Animation技術,使用CAKeyframeAnimation

  1. 導入你的代碼QuartzCore.framework到您的項目,並#import <QuartzCore/QuartzCore.h>
  2. 創建一個新的CAKeyframeAnimation對象,您可以將關鍵幀添加到。
  3. 創建定義縮放操作的CATransform3D值(不要被3D部分弄糊塗 - 您使用此對象在圖層上執行任何轉換)。
  4. 使用其setValues方法將動畫中的關鍵幀添加到CAKeyframeAnimation對象中,從而將其轉換爲其中一個關鍵幀。
  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"]; 

我會留下重複的「脈衝」動畫作爲練習:暗示,它涉及到animationDidStop方法!

另外一個注意事項 - CALayer動畫屬性的完整列表(其中「變換」是其中一個)可以找到here。快樂補間!

+0

非常感謝您的詳細解答。我已經解決了這個問題,使用CABasicAnimation和一個定時器。我相信你的代碼也能正常工作,所以你得到了接受。 ;) – DevZarak

相關問題