一创泄、簡(jiǎn)介
- 關(guān)鍵幀動(dòng)畫知染,也是CAPropertyAnimation的子類
二肋僧、與CABasicAnimation的區(qū)別
-
CABasicAnimation:
- 只能從一個(gè)數(shù)值(fromValue)變到另一個(gè)數(shù)值(toValue)
-
CAKeyframeAnimation:
- 會(huì)使用一個(gè)NSArray保存這些數(shù)值
CABasicAnimation可看做是只有2個(gè)關(guān)鍵幀的CAKeyframeAnimation關(guān)鍵幀動(dòng)畫
三、屬性說明
values 關(guān)鍵幀數(shù)組
- 上述的NSArray對(duì)象。里面的元素稱為
“關(guān)鍵幀”(keyframe)
嫌吠。 - 動(dòng)畫對(duì)象會(huì)在指定的時(shí)間(duration)內(nèi)止潘,依次顯示values數(shù)組中的每一個(gè)關(guān)鍵幀
path 路徑軌跡
- path:可以設(shè)置一個(gè)CGPathRef、CGMutablePathRef辫诅,讓圖層按照
路徑軌跡
移動(dòng)凭戴。 - path只對(duì)CALayer的anchorPoint和position起作用。
- 注意:
如果設(shè)置了path炕矮,那么values關(guān)鍵幀將被忽略
keyTimes:關(guān)鍵幀所對(duì)應(yīng)的時(shí)間點(diǎn)
- keyTimes:可以為對(duì)應(yīng)的關(guān)鍵幀指定對(duì)應(yīng)的時(shí)間點(diǎn)么夫,其取值范圍為0到1.0
- keyTimes中的每一個(gè)時(shí)間值都對(duì)應(yīng)values中的每一幀。如果沒有設(shè)置keyTimes肤视,各個(gè)關(guān)鍵幀的時(shí)間是平分的
四档痪、實(shí)例
-
實(shí)例:
- 控制器的view上,1.綠色的view钢颂,橢圓路徑位移钞它;2._redLayer 抖動(dòng)動(dòng)畫
代碼實(shí)現(xiàn):如下
#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 抖動(dòng) 動(dòng)畫 */
[self anim];
}
- (void)positionChange{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.duration = 2;
// 取消反彈
// 告訴在動(dòng)畫結(jié)束的時(shí)候不要移除
anim.removedOnCompletion = NO;
// 始終保持最新的效果
anim.fillMode = kCAFillModeForwards;
// Oval 橢圓 路徑軌跡
anim.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 300, 300)].CGPath;
// 將動(dòng)畫對(duì)象添加到 綠色視圖的layer上去
[_greenView.layer addAnimation:anim forKey:nil];
}
/**
* _redLayer 抖動(dòng)動(dòng)畫
*/
- (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