2025-02-10

先說明幾個基本的概念,方便理解後面的函數。

 屬性變化: 可以實現動畫效果的屬性包括位置(frame, bound), 對齊關系,透明度,背景色,內容拉伸,和transform(這個就多瞭,下面講)

timing curve: 時間曲線,以時間作為橫軸,其他值(這裡就是指需要變化的屬性)作為縱軸。在整個動畫持續時間內的函數曲線。
    ease in/ease out: 慢進/慢出,結合上面的時間曲線的概念,就是在動畫開始/或是結束的時候,屬性變化會減慢,看下面這個圖:是ease in ease out 也是默認的動畫效果(不是很好,網上隨便找的)
    liner: 線性變化,這個不講瞭,時間變化曲線一共就這兩種。默認是EaseInEaseOut,無疑EaseInEaseOut的效果會更加平滑,但是負荷也大些,不過一般問題不大。
    fade in /fade out: 淡入, 淡出,是一種動畫效果,就是逐漸消失,逐漸出現這種東西。
    講具體的函數前,先舉個例子先,
代碼
[UIView beginAnimations:@"ToggleViews" context:nil];

[UIView setAnimationDuration:1.0];

[UIView setAnimationCurve:UIViewAnimationEaseInOut];

// Make the animatable changes.
myView1.alpha = 0.0;
myView2.alpha = 1.0;

// Commit the changes and perform the animation.

[UIView commitAnimations];
    這段代碼就可以實現一個漂亮的淡入淡出的切換瞭,你所要做的,就是用begin/commit函數圈起一塊區域,然後把你想做的變化寫進去,無論有多少個,他們都會不被立刻執行,知道commit函數提交。簡單的說明下函數:
    beginAnimation:context:   兩個參數都是給delegate用的,一般nil也沒問題,animationID是標示當前動畫的名稱,在一個代理對應多端動畫時用於區別,context是void*,回調函數裡常用,用於傳遞額外的數據,保存上下文,避免使用全局變量。
    setAnimationCurve: 這個上面說過瞭,默認就是UIViewAnimationCurveEaseInOut,不寫也可以。
    setAnimationDuration:  動畫的長度,秒作為單位
    再補充個常用的函數,setAnimationRepeatCount: 可以重復動畫,有些場景下挺好用的。
    如果需要在動畫之前或是動畫之後做一些操作的話,可以定義代理(就是兩個回調函數)。看下面這個例子,在一個動畫後面接瞭另外一個動畫,熟悉代理的使用話,就沒啥可講的瞭。

代碼如下:

– (void)btn1Pressed
{
 [UIView beginAnimations:@"ShowHideView1" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:3.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(showHideDidStop:finished:context:)];
    // Make the animatable changes.
    m_myView1.alpha = 0.0;
    // Commit the changes and perform the animation.
    [UIView commitAnimations];
}

– (void)btn2Pressed
{
 [UIView beginAnimations:@"ShowHideView2" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:3.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(showHideDidStop:finished:context:)];
    // Make the animatable changes.
    m_myView2.alpha = 0.0;
    // Commit the changes and perform the animation.
    [UIView commitAnimations];
}

– (void)showHideDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
  if (animationID == @"ShowHideView1")
 {
  [UIView beginAnimations:@"ShowHideView1" context:nil];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
  [UIView setAnimationDuration:3.0];
  [UIView setAnimationDelay:2.0];
  m_myView1.alpha = 1.0;
  [UIView commitAnimations];
 }
 else if (animationID == @"ShowHideView2")
 {
  [UIView beginAnimations:@"ShowHideView2" context:nil];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
  [UIView setAnimationDuration:3.0];
  [UIView setAnimationDelay:2.0];
  m_myView2.alpha = 1.0;
  [UIView commitAnimations];
 }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *