萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 圖標抖動動畫實現:CAKeyframeAnimation 實戰

效果預覽:長按進入編輯模式,圖標抖動 + 刪除按鈕

模仿 iOS 主畫面長按進入「編輯模式」:圖標左右擺動抖動,左上角顯示刪除按鈕,再次點擊刪除或按 Home 鍵退出。

核心實現:CAKeyframeAnimation 旋轉動畫


// LHViewController.m
#import "LHViewController.h"

#define angleToRadian(x) ((x)/180.0*M_PI)

@interface LHViewController ()
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) IBOutlet UIButton *deleteButton;
@end

@implementation LHViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 長按手勢識別器
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 0.5; // 預設 0.5 秒
    [self.imageView addGestureRecognizer:longPress];
    self.imageView.userInteractionEnabled = YES;
    
    self.deleteButton.hidden = YES;
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        // 1. 啟動抖動動畫
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.values = @[@(angleToRadian(-7)), @(angleToRadian(7)), @(angleToRadian(-7))];
        animation.duration = 0.2;
        animation.repeatCount = HUGE_VALF; // 無限循環
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [self.imageView.layer addAnimation:animation forKey:@"wobble"];
        
        // 2. 顯示刪除按鈕
        self.deleteButton.hidden = NO;
    }
}

- (IBAction)deleteItem:(id)sender {
    // 移除動畫
    [self.imageView.layer removeAnimationForKey:@"wobble"];
    // 移除視圖
    [self.imageView removeFromSuperview];
    [self.deleteButton removeFromSuperview];
}

@end

關鍵技術點解析

1. CAKeyframeAnimation 關鍵幀動畫

  • keyPath: @"transform.rotation.z":繞 Z 軸旋轉 (2D 平面旋轉)
  • values:關鍵幀值陣列,`-7° → +7° → -7°` 形成左右擺動
  • duration:單個週期時長,0.2 秒體感輕快
  • repeatCount = HUGE_VALF:無限重複 (舊版用 `MAXFLOAT`)
  • timingFunction:緩動函數讓動畫更自然

2. 角度轉弧度宏


#define angleToRadian(x) ((x)/180.0*M_PI)
// 使用:@(angleToRadian(-7)) → -0.122 弧度

3. 長按手勢狀態機

  • `UIGestureRecognizerStatePossible` → `Began` (識別成功) → `Changed` → `Ended`/`Cancelled`
  • 只在 `Began` 狀態啟動動畫,避免重複添加

進階:完整「編輯模式」實現 (多圖標、同步抖動、完成按鈕)


@interface HomeViewController ()
@property (nonatomic, strong) NSMutableArray *iconViews; // 所有圖標視圖
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, assign) BOOL isEditingMode;
@end

- (void)enterEditingMode {
    self.isEditingMode = YES;
    self.doneButton.hidden = NO;
    
    for (UIView *iconView in self.iconViews) {
        // 添加抖動動畫
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
        anim.values = @[@(-0.05), @(0.05), @(-0.05)]; // 約 ±3°
        anim.duration = 0.15;
        anim.repeatCount = HUGE_VALF;
        [iconView.layer addAnimation:anim forKey:@"wobble"];
        
        // 添加刪除按鈕 (左上角紅圈叉)
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteBtn setImage:[UIImage imageNamed:@"delete_badge"] forState:UIControlStateNormal];
        deleteBtn.frame = CGRectMake(-8, -8, 24, 24);
        deleteBtn.tag = 999;
        [iconView addSubview:deleteBtn];
    }
}

- (void)exitEditingMode {
    self.isEditingMode = NO;
    self.doneButton.hidden = YES;
    
    for (UIView *iconView in self.iconViews) {
        [iconView.layer removeAnimationForKey:@"wobble"];
        [[iconView viewWithTag:999] removeFromSuperview];
    }
}

效能優化建議

  1. 圖層光柵化:`iconView.layer.shouldRasterize = YES; iconView.layer.rasterizationScale = [UIScreen mainScreen].scale;` 減少離屏渲染
  2. 動畫只加一次:進入編輯模式統一添加,退出統一移除,避免重複疊加
  3. 大量視圖考慮 CAShapeLayer / SpriteKit:上百個圖標同時動畫時 Core Animation 可能掉幀

Swift 5 版本


@objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
    guard gesture.state == .began else { return }
    
    let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
    animation.values = [-0.122, 0.122, -0.122] // ±7°
    animation.duration = 0.2
    animation.repeatCount = .infinity
    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
    imageView.layer.add(animation, forKey: "wobble")
    
    deleteButton.isHidden = false
}

@IBAction func deleteTapped(_ sender: UIButton) {
    imageView.layer.removeAnimation(forKey: "wobble")
    imageView.removeFromSuperview()
    deleteButton.removeFromSuperview()
}
copyright © 萬盛學電腦網 all rights reserved