您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

模擬 iOS 桌面圖標抖動效果的實作

編輯:iOS 相關教學

長按桌面圖標後,App 進入刪除模式時那種左右搖晃的動畫,是 iOS 辨識度很高的細節。用 CAKeyframeAnimation 就能重現。

#import "LHViewController.h"

// 角度轉弧度
#define angelToRandian(x) ((x) / 180.0 * M_PI)

@interface LHViewController ()

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation LHViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 長按才觸發抖動
    UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                      action:@selector(longPress:)];
    [self.imageView addGestureRecognizer:longPress];
}

- (void)longPress:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
        anim.keyPath = @"transform.rotation";
        // 三個關鍵幀:-7° → +7° → -7°,形成來回搖擺
        anim.values = @[@(angelToRandian(-7)),
                        @(angelToRandian(7)),
                        @(angelToRandian(-7))];
        anim.repeatCount = MAXFLOAT;   // 無限重複
        anim.duration = 0.2;           // 單次搖擺 0.2 秒
        [self.imageView.layer addAnimation:anim forKey:nil];

        self.btn.hidden = NO;          // 順便顯示刪除按鈕
    }
}

- (IBAction)delete:(id)sender
{
    [self.imageView removeFromSuperview];
    [self.btn removeFromSuperview];
}

@end

幾個細節值得注意

為什麼用 CAKeyframeAnimation 而非 CABasicAnimation?因為抖動是「往返」而非「單向」。若用 CABasicAnimation 搭配 autoreverses = YES,效果是從 0 轉到 -7° 再轉回 0,會多出一段歸位的停頓;而關鍵幀動畫可以直接指定 -7° → +7° → -7°,搖擺更連貫自然。

values 必須是弧度。transform.rotation 這個 keyPath 接受的是 CGFloat 弧度值,直接填 7 會變成 7 弧度(約 401°),畫面上就是瘋狂旋轉。這也是為什麼要寫 angelToRandian 這個巨集。

抖動幅度可以更真實。iOS 原生的抖動其實是「每個圖標的相位略有不同」,看起來比較像一群各自搖擺的物件而非整齊劃一的方塊。若想更貼近,可以為每個圖標隨機設定 timeOffset,或讓角度在 -6° 到 -9° 之間取隨機值,視覺上會自然很多。

另外提醒,keyPath 動畫是加在 layer 上的,不會改變 model layer 的實際 transform。因此在動畫進行期間若讀取 imageView.transform,拿到的仍是動畫前的值。若需要與手勢拖動搭配(例如進入抖動模式後還能拖著重新排列),記得改用 presentationLayer 取得當前實際呈現的狀態。

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