轉載自:http://www.jianshu.com/p/b05986ded337
一、簡介
-
關鍵幀動畫,也是CAPropertyAnimation的子類
二、與CABasicAnimation的區別
-
CABasicAnimation:
- 只能從一個數值(fromValue)變到另一個數值(toValue)
-
CAKeyframeAnimation:
- 會使用一個NSArray保存這些數值
-
CABasicAnimation可看做是隻有2個關鍵幀的CAKeyframeAnimation關鍵幀動畫
三、屬性說明
values 關鍵幀數組
- 上述的NSArray對象。裏面的元素稱爲
“關鍵幀”(keyframe)
。 - 動畫對象會在指定的時間(duration)內,依次顯示values數組中的每一個關鍵幀
path 路徑軌跡
- path:可以設置一個CGPathRef、CGMutablePathRef,讓圖層按照
路徑軌跡
移動。 - path只對CALayer的anchorPoint和position起作用。
- 注意:
如果設置了path,那麼values關鍵幀將被忽略
keyTimes:關鍵幀所對應的時間點
- keyTimes:可以爲對應的關鍵幀指定對應的時間點,其取值範圍爲0到1.0
- keyTimes中的每一個時間值都對應values中的每一幀。如果沒有設置keyTimes,各個關鍵幀的時間是平分的
四、實例
-
實例:
- 控制器的view上,1.綠色的view,橢圓路徑位移;2._redLayer 抖動動畫
-
代碼實現:如下
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *greenView;
@property (nonatomic, weak) CALayer *redLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1. 添加redLayer圖層 到view.layer上
CALayer *layer = [CALayer layer];
_redLayer = layer;
layer.backgroundColor = [UIColor redColor].CGColor;
layer.frame = CGRectMake(50, 50, 200, 200);
[self.view.layer addSublayer:_redLayer];
}
- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
/** 2. 綠色的view,橢圓路徑位移 */
[self positionChange];
/** _redLayer 抖動 動畫 */
[self anim];
}
- (void)positionChange{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.duration = 2;
// 取消反彈
// 告訴在動畫結束的時候不要移除
anim.removedOnCompletion = NO;
// 始終保持最新的效果
anim.fillMode = kCAFillModeForwards;
// Oval 橢圓 路徑軌跡
anim.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 300, 300)].CGPath;
// 將動畫對象添加到 綠色視圖的layer上去
[_greenView.layer addAnimation:anim forKey:nil];
}
/**
* _redLayer 抖動動畫
*/
- (void)anim{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.duration = 0.3;
anim.keyPath = @"transform";
NSValue *value = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((-15) / 180.0 * M_PI, 0, 0, 1)];
NSValue *value1 = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((15) / 180.0 * M_PI, 0, 0, 1)];
NSValue *value2 = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((-15) / 180.0 * M_PI, 0, 0, 1)];
anim.values = @[value,value1,value2];
anim.repeatCount = MAXFLOAT;
[_redLayer addAnimation:anim forKey:nil];
}
@end