iOS动画iOS 开发

CAKeyframeAnimation—关键帧动画

2015-11-12  本文已影响4017人  iOS_成才录

一、简介

结构图.png

二、与CABasicAnimation的区别

三、属性说明

values 关键帧数组

path 路径轨迹

keyTimes:关键帧所对应的时间点

四、实例

#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
上一篇 下一篇

猜你喜欢

热点阅读