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

iOS 手勢觸發水波紋點擊動畫實作

編輯:iOS 開發綜合

效果思路

點擊螢幕時,在手指落點處生成一個半透明的圓形視圖,先快速淡入,再一邊放大一邊淡出,視覺上就形成了水波向外擴散的效果。整個過程只需要一個預先建立好的 UIView,加上兩段串接的動畫即可。

預先準備波紋視圖

在 viewDidLoad 中建立一個直徑 300×300 的圓形視圖,透過 cornerRadius 取半徑值並開啟 masksToBounds 裁切,再把初始透明度設為 0,讓它在未被觸發前保持隱形。

- (void)viewDidLoad {
    [super viewDidLoad];
    RippleView = [[UIView alloc] initWithFrame:(CGRect){0, 0, 300, 300}];
    RippleView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    RippleView.layer.cornerRadius = 150;
    RippleView.layer.masksToBounds = YES;
    RippleView.alpha = 0;
}

在 touchesBegan 中觸發動畫

首先在 touchesBegan:withEvent: 裡取得觸控點座標,把波紋視圖加入畫面並對齊手指位置,接著用兩段動畫接力完成效果。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];

    [self.view addSubview:RippleView];
    RippleView.center = location;
    RippleView.transform = CGAffineTransformMakeScale(0.5, 0.5);

    // 第一段:快速淡入,讓波紋瞬間出現
    [UIView animateWithDuration:0.1 animations:^{
        RippleView.alpha = 1;
        self.view.alpha = 0.3;
    }];

    // 第二段:放大並淡出,形成擴散感
    [UIView animateWithDuration:0.7
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
        RippleView.transform = CGAffineTransformMakeScale(1, 1);
        RippleView.alpha = 0;
        self.view.alpha = 1;
    } completion:^(BOOL finished) {
        [RippleView removeFromSuperview];
    }];
}

幾個容易忽略的細節

起始縮放設為 0.5,是為了讓波紋從「比最終尺寸小一半」的位置長出來,放大過程才有明確的方向感;動畫選用 UIViewAnimationOptionCurveEaseInOut,起步與收尾都較柔和,比線性更貼近真實水波;最後在 completion 中把視圖從父視圖移除,避免每次點擊都殘留節點造成記憶體累積。

若希望波紋顏色可換,只需調整 backgroundColor 的 alpha 值;若要在列表或按鈕上使用,則建議把這段邏輯封裝成自訂 UIView 子類,改由 touchesBegan: 之外的方式呼叫,以免與既有手勢衝突。

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