您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 CATransition 實現多種轉場動畫效果

編輯:iOS 開發綜合

Core Animation 中的 CATransition 能輕鬆為圖層添加各種轉場效果。下面透過一個範例,展示如何搭配 UISegmentedControl 切換不同動畫類型。

頭檔 (.h)

@interface XXXViewController : UITViewController {
  int direction;
  BOOL isBlue;
}

實作檔 (.m)

記得在頂部匯入:#import <QuartzCore/QuartzCore.h>

在 viewDidLoad 中建立一個分段控制器、一個背景視圖與兩個重疊的圖片視圖,再擺上一顆「開始」按鈕即可。

動畫的核心在於 startAction: 方法:

- (void)startAction:(id)sender{
  CATransition *animation = [CATransition animation];
  animation.delegate = self;
  animation.duration = 1.0f;
  animation.timingFunction = UIViewAnimationCurveEaseInOut;

  switch ([(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex]) {
    case 0: animation.type = @"rippleEffect"; break; // 漣漪
    case 1: animation.type = @"pageCurl"; break; // 翻頁捲起
    case 2: animation.type = @"pageUnCurl"; break; // 翻頁展開
    case 3: animation.type = @"suckEffect"; break; // 吸入
    default: break;
  }

  switch (direction) {
    case 0: animation.subtype = kCATransitionFromRight; break;
    case 1: animation.subtype = kCATransitionFromTop; break;
    case 2: animation.subtype = kCATransitionFromLeft; break;
    case 3: animation.subtype = kCATransitionFromBottom; break;
    default: break;
  }

  UIView *bgView = [self.view viewWithTag:150];
  NSInteger front = [[bgView subviews] indexOfObject:[bgView viewWithTag:151]];
  NSInteger back = [[bgView subviews] indexOfObject:[bgView viewWithTag:152]];
  if (isBlue) {
    [bgView exchangeSubviewAtIndex:front withSubviewAtIndex:back];
  } else {
    [bgView exchangeSubviewAtIndex:back withSubviewAtIndex:front];
  }
  [[bgView layer] addAnimation:animation forKey:@"animation"];
  if (++direction > 3) direction -= 4;
  isBlue = !isBlue;
}

除了 rippleEffect 之外,type 還可設定為 cube(立方體翻轉)、oglFlip(層翻轉)、cameraIrisHollowOpen/cameraIrisHollowClose(光圈開合)等值,搭配不同的 subtype 方向,就能變化出豐富多樣的轉場效果。透過交換兩個圖片視圖的層級順序,再套用動畫,即可呈現圖形切換的視覺饗宴。

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