核心动画03——CAKeyframeAnimation(关键帧动画)
一、简介
关键帧动画,也是 CAPropertyAnimation 的子类,与CABasicAnimation的区别是:
CABasicAnimation只能从一个数值(fromValue)变到另一个数值(toValue),而CAKeyframeAnimation会使用一个NSArray保存这些数值
属性说明
属性 | 说明 |
---|---|
values | 上述的NSArray对象。里面的元素称为“关键帧”(keyframe)。动画对象会在指定的时间(duration)内,依次显示values数组中的每一个关键帧 |
path | 可以设置一个CGPathRef、CGMutablePathRef,让图层按照路径轨迹移动。path只对CALayer的anchorPoint和position起作用。如果设置了path,那么values将被忽略 |
keyTimes | 可以为对应的关键帧指定对应的时间点,其取值范围为0到1.0,keyTimes中的每一个时间值都对应values中的每一帧。如果没有设置keyTimes,各个关键帧的时间是平分的 |
CABasicAnimation可看做是只有2个关键帧的CAKeyframeAnimation
二、代码示例
//
// ViewController.m
// 03_UIView70_图片抖动效果
//
// Created by 杞文明 on 17/6/15.
// Copyright © 2017年 杞文明. All rights reserved.
//
#import "ViewController.h"
#define angle2Rad(angle) ((angle)/180.0 * M_PI)
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//抖动的点击
- (IBAction)shakeClick:(id)sender {
[self shakeAnim1];
}
//路径的点击
- (IBAction)pathClick:(id)sender {
[self pathAnim1];
}
//路径动画
-(void)pathAnim1{
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50, 50)];
[path addLineToPoint:CGPointMake(200, 200)];
[path addLineToPoint:CGPointMake(300, 150)];
anim.keyPath = @"position";
anim.path = path.CGPath;
anim.autoreverses = YES;
anim.duration = 2;
[self.imageView.layer addAnimation:anim forKey:nil];
}
//抖动动画
-(void)shakeAnim1{
//1.创建动画
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
//2.设置属性
anim.keyPath = @"transform.rotation";
anim.values = @[@(angle2Rad(-6)),@(angle2Rad(6)),@(angle2Rad(-6))];
//anim.repeatCount = MAXFLOAT;
anim.repeatCount = 3;
anim.duration = 0.5;
//一种方式是设置这个值,另外一种方式是添加一个值
//anim.autoreverses = YES;
//3.添加动画
[self.imageView.layer addAnimation:anim forKey:nil];
}
@end