iOS基本動畫/主要畫面格動畫/利用easing 函式實現物理動畫效果
先說下基本動畫部分
基本動畫部分比較簡單, 但能實現的動畫效果也很局限
使用方法大致為:
#1. 建立原始UI或者畫面
#2. 建立CABasicAnimation執行個體, 並設定keypart/duration/fromValue/toValue
#3. 設定動畫最終停留的位置
#4. 將配置好的動畫添加到layer層中
舉個例子, 比如實現一個圓形從上往下移動, 上代碼:
//設定原始畫面 UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; showView.layer.masksToBounds = YES; showView.layer.cornerRadius = 50.f; showView.layer.backgroundColor = [UIColor redColor].CGColor; [self.view addSubview:showView]; //建立基本動畫 CABasicAnimation *basicAnimation = [CABasicAnimation animation]; //設定屬性 basicAnimation.keyPath = @"position"; basicAnimation.duration = 4.0f; basicAnimation.fromValue = [NSValue valueWithCGPoint:showView.center]; basicAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(50, 300)]; //設定動畫結束位置 showView.center = CGPointMake(50, 300); //添加動畫到layer層 [showView.layer addAnimation:basicAnimation forKey:nil];
接下來說下主要畫面格動畫
其實跟基本動畫差不多, 只是能設定多個動畫路徑 使用方法也類似, 大致為
#1. 建立原始UI或者畫面
#2. 建立CAKeyframeAnimation執行個體, 並設定keypart/duration/values 相比基本動畫只能設定開始和結束點, 主要畫面格動畫能添加多個動畫路徑點
#3. 設定動畫最終停留的位置
#4. 將配置好的動畫添加到layer層中
舉個例子, 紅色圓形左右晃動往下墜落 上代碼:
//設定原始畫面 UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; showView.layer.masksToBounds = YES; showView.layer.cornerRadius = 50.f; showView.layer.backgroundColor = [UIColor redColor].CGColor; [self.view addSubview:showView]; //建立主要畫面格動畫 CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animation]; //設定動畫屬性 keyFrameAnimation.keyPath = @"position"; keyFrameAnimation.duration = 4.0f; keyFrameAnimation.values = @[[NSValue valueWithCGPoint:showView.center], [NSValue valueWithCGPoint:CGPointMake(100, 100)], [NSValue valueWithCGPoint:CGPointMake(50, 150)], [NSValue valueWithCGPoint:CGPointMake(200, 200)]]; //設定動畫結束位置 showView.center = CGPointMake(200, 200); //添加動畫到layer層 [showView.layer addAnimation:keyFrameAnimation forKey:nil];
最後是利用easing 函式配合主要畫面格動畫實現比較複雜的物理性動畫
先說說什麼是easing 函式, 就是有高人寫了一個庫可以計算出類比物理性動畫(比如彈簧效果)所要的路徑
Github地址: https://github.com/YouXianMing/EasingAnimation
具體有哪些動畫效果可看庫中的easing 函式查詢表, 簡單舉個小球落地的效果
上代碼:
//設定原始畫面 UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; showView.layer.masksToBounds = YES; showView.layer.cornerRadius = 50.f; showView.layer.backgroundColor = [UIColor redColor].CGColor; [self.view addSubview:showView]; //建立主要畫面格動畫 CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animation]; //設定動畫屬性 keyFrameAnimation.keyPath = @"position"; keyFrameAnimation.duration = 4.0f; //關鍵處, 在這裡使用的easing 函式計算點路徑 keyFrameAnimation.values = [YXEasing calculateFrameFromPoint:showView.center toPoint:CGPointMake(50, 300) func:BounceEaseOut frameCount:4.0f * 30]; //設定動畫結束位置 showView.center = CGPointMake(50, 300); //添加動畫到layer層 [showView.layer addAnimation:keyFrameAnimation forKey:nil];
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!