第二十七章 核心动画

  • 核心动画基本概念
  • 基本动画
  • 关键帧动画
  • 动画组
  • 转场动画

Core Animation简介

  • Core Animation,中文翻译为核心动画,它是一组非常强大的动画处理API,使用它能做出非常炫丽的动画效果,而且往往是事半功倍。也就是说,使用少量的代码就可以实现非常强大的功能。
  • Core Animation可以用在Mac OS X和iOS平台。
  • Core Animation的动画执行过程都是在后台操作的,不会阻塞主线程。
  • 要注意的是,Core Animation是直接作用在CALayer上的,并非UIView。

核心动画继承结构

核心动画继承结构

Core Animation的使用步骤

  • 开发步骤:
    1. 首先得有CALayer
    2. 初始化一个CAAnimation对象,并设置一些动画相关属性
    3. 通过调用CALayer的addAnimation:forKey:方法,增加CAAnimation对象到CALayer中,这样就能开始执行动画了
    4. 通过调用CALayer的removeAnimationForKey:方法可以停止CALayer中的动画

CAAnimation——简介

  • 是所有动画对象的父类,负责控制动画的持续时间和速度,是个抽象类,不能直接使用,应该使用它具体的子类
  • 属性说明:(红色代表来自CAMediaTiming协议的属性)
    • duration:动画的持续时间
    • repeatCount:重复次数,无限循环可以设置HUGE_VALF或者MAXFLOAT
    • repeatDuration:重复时间
    • removedOnCompletion:默认为YES,代表动画执行完毕后就从图层上移除,图形会恢复到动画执行前的状态。如果想让图层保持显示动画执行后的状态,那就设置为NO,不过还要设置fillMode为kCAFillModeForwards
    • fillMode:决定当前对象在非active时间段的行为。比如动画开始之前或者动画结束之后
    • beginTime:可以用来设置动画延迟执行时间,若想延迟2s,就设置为CACurrentMediaTime()+2,CACurrentMediaTime()为图层的当前时间
    • timingFunction:速度控制函数,控制动画运行的节奏
    • delegate:动画代理

CAAnimation——动画填充模式

  • fillMode属性值(要想fillMode有效,最好设置removedOnCompletion = NO)

  • kCAFillModeRemoved 这个是默认值,也就是说当动画开始前和动画结束后,动画对layer都没有影响,动画结束后,layer会恢复到之前的状态

  • kCAFillModeForwards 当动画结束后,layer会一直保持着动画最后的状态
  • kCAFillModeBackwards 在动画开始前,只需要将动画加入了一个layer,layer便立即进入动画的初始状态并等待动画开始。
  • kCAFillModeBoth 这个其实就是上面两个的合成.动画加入后开始之前,layer便处于动画初始状态,动画结束后layer保持动画最后的状态

CAAnimation——速度控制函数

  • 速度控制函数(CAMediaTimingFunction)
    • kCAMediaTimingFunctionLinear(线性):匀速,给你一个相对静态的感觉
    • kCAMediaTimingFunctionEaseIn(渐进):动画缓慢进入,然后加速离开
    • kCAMediaTimingFunctionEaseOut(渐出):动画全速进入,然后减速的到达目的地
    • kCAMediaTimingFunctionEaseInEaseOut(渐进渐出):动画缓慢的进入,中间加速,然后减速的到达目的地。这个是默认的动画行为。

CAAnimation——动画代理方法

CAAnimation在分类中定义了代理方法

@interface NSObject (CAAnimationDelegate)

/* Called when the animation begins its active duration. */

- (void)animationDidStart:(CAAnimation *)anim;

/* Called when the animation either completes its active duration or
 * is removed from the object it is attached to (i.e. the layer). 'flag'
 * is true if the animation reached the end of its active duration
 * without being removed. */

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag;

@end

CALayer上动画的暂停和恢复

#pragma mark 暂停CALayer的动画
-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];

    // 让CALayer的时间停止走动
      layer.speed = 0.0;
    // 让CALayer的时间停留在pausedTime这个时刻
    layer.timeOffset = pausedTime;
}

CALayer上动画的恢复

#pragma mark 恢复CALayer的动画
-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = layer.timeOffset;
    // 1. 让CALayer的时间继续行走
      layer.speed = 1.0;
    // 2. 取消上次记录的停留时刻
      layer.timeOffset = 0.0;
    // 3. 取消上次设置的时间
      layer.beginTime = 0.0;    
    // 4. 计算暂停的时间(这里也可以用CACurrentMediaTime()-pausedTime)
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    // 5. 设置相对于父坐标系的开始时间(往后退timeSincePause)
      layer.beginTime = timeSincePause;
}

CAPropertyAnimation

  • 是CAAnimation的子类,也是个抽象类,要想创建动画对象,应该使用它的两个子类:
    • CABasicAnimation
    • CAKeyframeAnimation

属性说明: keyPath:通过指定CALayer的一个属性名称为keyPath(NSString类型),并且对CALayer的这个属性的值进行修改,达到相应的动画效果。比如,指定@“position”为keyPath,就修改CALayer的position属性的值,以达到平移的动画效果

CABasicAnimation——基本动画

  • 基本动画,是CAPropertyAnimation的子类
  • 属性说明:
    • fromValue:keyPath相应属性的初始值
    • toValue:keyPath相应属性的结束值
  • 动画过程说明:
    • 随着动画的进行,在长度为duration的持续时间内,keyPath相应属性的值从fromValue渐渐地变为toValue
    • keyPath内容是CALayer的可动画Animatable属性
    • 如果fillMode=kCAFillModeForwards同时removedOnComletion=NO,那么在动画执行完毕后,图层会保持显示动画执行后的状态。但在实质上,图层的属性值还是动画执行前的初始值,并没有真正被改变。

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

CAAnimationGroup——动画组

  • 动画组,是CAAnimation的子类,可以保存一组动画对象,将CAAnimationGroup对象加入层后,组中所有动画对象可以同时并发运行

  • 属性说明:

    • animations:用来保存一组动画对象的NSArray
    • 默认情况下,一组动画对象是同时运行的,也可以通过设置动画对象的beginTime属性来更改动画的开始时间

转场动画——CATransition

  • CATransition是CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点
  • UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果
  • 动画属性:
    • type:动画过渡类型
    • subtype:动画过渡方向
    • startProgress:动画起点(在整体动画的百分比)
    • endProgress:动画终点(在整体动画的百分比)

转场动画过渡效果

转场动画过渡效果

suckEffect:相对于父控件进行抽离,可以将需要抽离的图片放置在一个与之同等大小的父控件之上,这样效果更好

使用UIView动画函数实现转场动画——单视图

+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;
  • 参数说明:
    • duration:动画的持续时间
    • view:需要进行转场动画的视图
    • options:转场动画的类型
    • animations:将改变视图属性的代码放在这个block中
    • completion:动画结束后,会自动调用这个block

使用UIView动画函数实现转场动画——双视图

+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion;
  • 参数说明:
    • duration:动画的持续时间
    • options:转场动画的类型
    • animations:将改变视图属性的代码放在这个block中
    • completion:动画结束后,会自动调用这个block

CADisplayLink

  • CADisplayLink是一种以屏幕刷新频率触发的时钟机制,每秒钟执行大约60次左右
  • CADisplayLink是一个计时器,可以使绘图代码与视图的刷新频率保持同步,而- - NSTimer无法确保计时器实际被触发的准确时间
  • 使用方法:
    • 定义CADisplayLink并制定触发调用方法
    • 将显示链接添加到主运行循环队列

举例说明

基本动画


    // 触摸点
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    // 基本动画
    CABasicAnimation * animation = [CABasicAnimation animation];

    // 设置哪个属性需要修改动画
    animation.keyPath = @"position";

    // 设置值
    animation.toValue = [NSValue valueWithCGPoint:point];

    // 保存动画执行完成后的状态
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;

    // 添加动画
    [self.blueView.layer addAnimation:animation forKey:nil];

核心动画

核心关键路径动画

    #define angle(a) ((a)/180.0 * M_PI)
    // 添加核心动画
    CAKeyframeAnimation * key = [CAKeyframeAnimation animation];

    // 设置需要修改的属性
    key.keyPath = @"transform.rotation";

    // 设置修改
    key.values = @[@(angle(0)),@(angle(5)),@(angle(10)),@(angle(15)),@(angle(10)),@(angle(5)),@(angle(0)),@(angle(-5)),@(angle(-10)),@(angle(-15)),@(angle(-10)),@(angle(-5)),@(angle(0))];

    // 重复次数
    key.repeatCount = MAXFLOAT;

    // 添加到控件
    [self.blueView.layer addAnimation:key forKey:nil];

核心关键路径,指定路径


        // 添加核心动画
    CAKeyframeAnimation * key = [CAKeyframeAnimation animation];

    // 设置需要修改的属性
    key.keyPath = @"position";

    // 设置修改
    UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, self.view.bounds.size.width - 100, self.view.bounds.size.height - 100)];

    // 转化路径
    key.path = path.CGPath;

    // 重复次数
    key.repeatCount = MAXFLOAT;

    // 添加到控件
    [self.blueView.layer addAnimation:key forKey:nil];

自定义路径,指定动画

指定viewController的view类为我们自定义的类,这样我们才可以重写drawRect方法

  #import "JXView.h"

@interface JXView ()

/** 路径 */
@property (nonatomic,strong) UIBezierPath * path;

@end

@implementation JXView

- (void)drawRect:(CGRect)rect {
    [self.path stroke];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取当前手指触摸点
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];

    // 创建曲线
    UIBezierPath * path = [UIBezierPath bezierPath];
    [path moveToPoint:point];
    self.path = path;


}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取当前手指触摸点
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];

    [self.path addLineToPoint:point];
    // 重绘
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 创建动画
    CAKeyframeAnimation * key = [CAKeyframeAnimation animation];

    key.keyPath = @"position";

    // 动画路径
    key.path = self.path.CGPath;

    key.duration = 5;

    // 重复次数
    key.repeatCount = MAXFLOAT;

    [[[self.subviews firstObject] layer] addAnimation:key forKey:nil];
}
@end

转场动画

转场动画必须跟转场代码写在一起


    // 转场代码
    NSArray * imageArray = @[@"APPLE0",@"APPLE1",@"APPLE2",@"APPLE3",@"APPLE4",@"APPLE5",@"APPLE6",@"APPLE7",@"APPLE8"];
    NSInteger index = arc4random_uniform(9) ;
    UIImage * image = [UIImage imageNamed:imageArray[index]];
    self.imageV.image = image;

    // 转场动画  (转场代码必须跟转场动画在一起)
    // 添加转场动画
    CATransition * transition = [CATransition animation];

    NSArray * tranArray = @[@"fade",@"push",@"reveal",@"moveIn",@"cube",@"oglFlip",@"suckEffect",@"rippleEffect",@"pageCurl",@"pageCurl",@"cameraIrisHollowOpen",@"cameraIrisHollowClose"];
    NSInteger tranIndex = arc4random_uniform(12);
    NSString * type = tranArray[tranIndex];

    // suckEffect:相对于父控件进行抽离,可以将需要抽离的图片放置在一个与之同等大小的父控件之上,这样效果更好
    // 设置转场动画
    transition.type = type;

    // 添加到控件上
    [self.imageV.layer addAnimation:transition forKey:nil];

动画组

    // 动画组
    CAAnimationGroup * group = [CAAnimationGroup animation];

    // 基础动画,移动
    CABasicAnimation * basic = [CABasicAnimation animation];
    basic.keyPath = @"position";
    basic.toValue = [NSValue valueWithCGPoint:CGPointZero];

    // 基础动画,缩放
    CABasicAnimation * scale = [CABasicAnimation animation];
    scale.keyPath = @"transform.scale";
    scale.toValue = @0.5;

    //基础动画,旋转
    CABasicAnimation * transform = [CABasicAnimation animation];
    transform.keyPath = @"transform.rotation";
    transform.toValue = [NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(200), arc4random_uniform(200))];

    group.animations = @[basic,scale,transform];
    group.duration = 3;

    // 将动画组添加到控件上
    [self.drawView.layer addAnimation:group forKey:nil];

图片倒影

1.自定义一个view,将其主层的类改成复制层

 #import "JXRefectionView.h"

@implementation JXRefectionView

// 表示将主层返回的是一个复制图层,默认的是CALayer
+ (Class)layerClass {
    return [CAReplicatorLayer class];
}

@end

2.在主视图上讲复制图层进行旋转等操作

#import "ViewController.h"
#import "JXRefectionView.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet JXRefectionView *JXView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    CAReplicatorLayer * repL = (CAReplicatorLayer *)self.JXView.layer;
    repL.instanceCount = 2;
    repL.instanceTransform = CATransform3DMakeTranslation(0, repL.frame.size.height, 0);
    repL.instanceTransform = CATransform3DRotate(repL.instanceTransform, M_PI, 1, 0, 0);
    repL.instanceRedOffset = -0.1;
    repL.instanceGreenOffset = -0.1;
    repL.instanceBlueOffset = -0.1;
}

@end

results matching ""

    No results matching ""