您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

用 CAKeyframeAnimation 為按鈕加上彈出動畫

編輯:iOS 技巧大全
[摘要]本文示範如何使用 CAKeyframeAnimation 為按鈕製作類似「彈出」的縮放動畫,透過多個關鍵影格讓元素出現時更具活潑的視覺效果,是學習 Core Animation 的實用範例。

為介面元素加入動畫,往往能大幅提升使用者的操作體驗。以下程式碼示範如何為一個按鈕製作類似彈出(pop up)效果的縮放動畫,讓它出現時先縮小、再放大、然後回彈到正常大小:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(10, 100, 100, 200); button.backgroundColor=[UIColor redColor]; [button setTitle:@"按鈕" forState:UIControlStateNormal]; [self.view addSubview:button]; //按鈕的動畫效果 [self buttonAnimation:button]; } //按鈕出現的時候有一個動畫效果 - (void)buttonAnimation:(UIButton *)sender { CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; CATransform3D scale1 = CATransform3DMakeScale(0.5, 0.5, 1); CATransform3D scale2 = CATransform3DMakeScale(1.2, 1.2, 1); CATransform3D scale3 = CATransform3DMakeScale(0.9, 0.9, 1); CATransform3D scale4 = CATransform3DMakeScale(1.0, 1.0, 1); NSArray *frameValues = [NSArray arrayWithObjects: [NSValue valueWithCATransform3D:scale1], [NSValue valueWithCATransform3D:scale2], [NSValue valueWithCATransform3D:scale3], [NSValue valueWithCATransform3D:scale4], nil]; [animation setValues:frameValues]; NSArray *frameTimes = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:0.9], [NSNumber numberWithFloat:1.0], nil]; [animation setKeyTimes:frameTimes]; animation.fillMode = kCAFillModeForwards; animation.duration = 0.3f; [sender.layer addAnimation:animation forKey:@"DSPopUpAnimation"]; } 

這個動畫的核心在於 CAKeyframeAnimation(關鍵影格動畫)。我們先定義幾個縮放比例(0.5 → 1.2 → 0.9 → 1.0),再透過 setValues 設定各影格的變形值、setKeyTimes 設定每個影格發生的時間點,就能創造出先縮後彈再回穩的活潑效果。fillMode 設為 Forwards 可讓動畫停在最後狀態,duration 則控制整體節奏。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved