核心动画

来源:互联网 发布:json文件修改器 编辑:程序博客网 时间:2024/06/05 17:14

CALayer

简介

  • UIView之所以能显示在屏幕上,完全是因为它内部的一个图层
  • 在创建UIView对象时,UIView内部会自动创建一个图层(即CALayer对象),通过UIView的layer属性可以访问这个层
    @property(nonatomic,readonly,strong) CALayer *layer;
  • 当UIView需要显示到屏幕上时,会调用drawRectangle:方法进行绘图,并且会将所有内容绘制在自己的图层上,绘图完毕后,系统会将图层拷贝到屏幕上,于是就完成了UIView的显示
  • 换句话说,UIView本身不具备显示的功能,是它内部的层才有显示功能

基本使用

  • 通过操作CALayer对象,可以很方便地调整UIView的一些外观属性,比如
    • 阴影
//设置阴影//opacity:不透明度_imageview.layer.shadowOpacity = 1;_imageview.layer.shadowOffset = CGSizeMake(10, 10);//注意:图层的颜色都是核心绘图框架,通常CGColor_imageview.layer.shadowColor = [UIColor redColor].CGColor;_imageview.layer.shadowRadius = 10;
  • 圆角大小
//cornerRadiu设置控件的主层边框_imageview.layer.cornerRadius = 50;
  • 边框宽度和颜色
_imageview.layer.borderColor = [UIColor purpleColor].CGColor;_imageview.layer.borderWidth = 2;
  • ……..
    • 裁剪
_imageview.layer.cornerRadius = 200;//如果是yes,表示需要裁剪。裁剪的是主层。超出主层边框的内容会被全部裁剪掉。缺点:边缘可能会有锯齿_imageview.layer.masksToBounds = YES; 
  • 旋转、缩放
 _imageview.layer.transform = CATransform3DMakeScale(0.5, 0.5, 0.5); _imageview.layer.transform = CATransform3DMakeRotation(M_PI, 1, 1, 0); //快速进行图层缩放,KVC [_imageview.layer setValue:@0.5 forKeyPath:@"transform.scale"];    
  • 新建图层
 CALayer *layer = [CALayer layer]; layer.frame = CGRectMake(50, 100, 200, 200); layer.contents = (id)[UIImage imageNamed:@"阿狸头像.png"].CGImage; [self.view.layer addSublayer:layer];      
  • 还可以给图层添加动画,来实现一些比较炫酷的效果

关于CALayer的疑惑

  • 首先
    • CALayer是定义在QuatrzCore框架中的
    • CGImageRef、CGColorRef两种数据类型是定义在CoreGraphics框架中的
    • UIColor、UIImage是定义在UIKit框架中的
  • 其次
    • QuartzCore框架和CoreGraphics框架是可以跨平台使用的,在iOS和Mac OS X上都能使用
    • 但是UIKit只能在iOS中使用
    • 为了保证可移植性,QuartzCore不能使用UIImage、UIColor,只能用CGImageRef 、CGColorRef

UIView和CALayer的选择

  • 通过CALayer,就能做出跟UIImageView一样的界面效果
  • 既然CALayer和UIView都能实现相同的显示效果,那究竟该选择谁好呢
    • 其实,对比CALayer,UIView多了一个事件处理的功能。也就是说,CALayer不能处理用户的触摸事件,而UIView可以。因为UIView 继承自UIResponsed,CALayerc继承自NSObject
    • 所以,如果显示出来的东西需要跟用户进行交互的话,用UIView,如果不需要跟用户进行交互,用UIView或者CALayer都可以
    • 当然,CALayer的性能会高一些,因为它少了事件处理的功能,更加轻量级

position和anchorPoint

  • CALayer有2个非常重要的属性:position和anchorPoint
    • @property CGPoint position;
      • 用来设置CALayer在父层中的位置
      • 以父层的左上角为原点(0,0)
    • @property CGPoint anchorPoint;
      • 称为“定位点”、“锚点”
      • 决定着CALayer身上的哪个点会在position属性所指的位置
      • 以自己的左上角为远点(0,0)
      • 它的x、y取值范围都是0~1,默认值为(0.5,0.5)

隐式动画

  • 每一个UIView内部都默认关联着一个CALayer,我们可用称这个Layer为RootLoayer(根层)
  • 所有的非Root Layer,也就是手动创建的CALayer对象,都存在着隐式动画
  • 什么是隐式动画
    • 当对非Root Layer的部分属性进行修改时,默认会自动产生一些动画效果
    • 而这些属性称为Animatable Properties(可动画属性)
    • 角度转弧度:角度/180.0 * M_PI
    • -

Core Animation

简介

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

继承结构

  • 注意:图中的黑色虚线代表“继承”某个类,红色虚线代表“遵守”某个协议
    这里写图片描述

CAAnimation

简介

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

动画填充模式

  • fillMode属性值(要想fillMode有效,最好设置removedOnCompletion = NO)
  • kCAFillModeRemoved 这个是默认值,也就是说当动画开始前和动画结束后,动画对layer都没有影响,动画结束后,layer会恢复到之前的状态
  • kCAFillModeForwards 当动画结束后,layer会一直保持着动画最后的状态
  • kCAFillModeBackwards 在动画开始前,只需要将动画加入了一个layer,layer便立即进入动画的初始状态并等待动画开始。
  • kCAFillModeBoth 这个其实就是上面两个的合成.动画加入后开始之前,layer便处于动画初始状态,动画结束后layer保持动画最后的状态

速度控制函数

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

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;}#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,那么在动画执行完毕后,图层会保持显示动画执行后的状态。但在实质上,图层的属性值还是动画执行前的初始值,并没有真正被改变。
    //创建动画    CABasicAnimation *anim = [CABasicAnimation animation];    //    //描述下修改哪个属性产生动画。只能是layer的属性    //    anim.keyPath = @"position";    //    //设置值    //    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(250, 250)];    //缩放    anim.keyPath = @"transform.scale";    //设置值    anim.toValue = @0.5;    //设置动画执行次数.MAXFLOAT表示无限次执行    anim.repeatCount = MAXFLOAT;    //设置动画完成的时候不要移除动画    anim.removedOnCompletion = NO;    //设置动画执行完成要保持最新的效果    anim.fillMode = kCAFillModeForwards;    [_imageview.layer addAnimation:anim forKey:nil];

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

#define angle2Radion(angle) (angle / 180.0 * M_PI)    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];    anim.keyPath = @"transform.rotation";    anim.values = @[@(angle2Radion(-5)),@(angle2Radion(5)),@(angle2Radion(-5))];    anim.duration = 1.0;    anim.repeatCount = MAXFLOAT;    [_imageview.layer addAnimation:anim forKey:nil];
  • 默认锚点为中心点,可以设置
    _imageview.layer.anchorPoint = CGPointZero;
  • 添加路径
    anim.keyPath = @"position";
    anim.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(30, 30, 100, 100)].CGPath;

画板

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    //touch    UITouch *touch = [touches anyObject];    NSLog(@"touch---%@",touches);    //获取手指的触点    CGPoint curP = [touch locationInView:self];    //创建路径    UIBezierPath *path = [UIBezierPath bezierPath];    _path = path;    //设置起点    [path moveToPoint:curP];}-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    UITouch *touch = [touches anyObject];    //获取手指的触点    CGPoint curP = [touch locationInView:self];    [_path addLineToPoint:curP];    [self setNeedsDisplay];}-(void)drawRect:(CGRect)rect{    [_path stroke];}
  • 让图片沿着所画的路径移动
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];    anim.keyPath = @"position";    anim.path = _path.CGPath;    anim.duration = 1;    anim.repeatCount = MAXFLOAT;    [[[self.subviews firstObject] layer] addAnimation:anim forKey:nil];}

转场动画

  • CATransition是CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点
  • UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果
  • 动画属性:
    • type:动画过渡类型
    • subtype:动画过渡方向
    • startProgress:动画起点(在整体动画的百分比)
    • endProgress:动画终点(在整体动画的百分比)
  • 代码
static int i = 2;-(void)trans{    //转场代码    if (i == 4) {        i = 1;    }    //加载图片名称    NSString *imageN = [NSString stringWithFormat:@"%d",i];    _imageview.image = [UIImage imageNamed:imageN];    i++;    //转场动画    CATransition *anim = [CATransition animation];    anim.type = @"suckEffect"; //suckEffect是往父控件左上角抽的    [_imageview.layer addAnimation:anim forKey:nil];}
  • 转场动画过渡效果
    这里写图片描述

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

动画组

  • 动画组,是CAAnimation的子类,可以保存一组动画对象,将CAAnimationGroup对象加入层后,组中所有动画对象可以同时并发运行
  • 属性说明:
    • animations:用来保存一组动画对象的NSArray
    • 默认情况下,一组动画对象是同时运行的,也可以通过设置动画对象的beginTime属性来更改动画的开始时间
  • 代码
    CAAnimationGroup *group = [CAAnimationGroup animation];    CABasicAnimation *scale = [CABasicAnimation animation];    scale.keyPath = @"transform.scale";    scale.toValue = @0.5;    CABasicAnimation *rotation = [CABasicAnimation animation];    rotation.keyPath = @"transform.rotation";    rotation.toValue = @(M_PI_4);    CABasicAnimation *position = [CABasicAnimation animation];    position.keyPath = @"position";    position.toValue = [NSValue valueWithCGPoint:CGPointMake(arc4random_uniform(200), arc4random_uniform(200))];    group.animations = @[scale,rotation,position];    [_imageview.layer addAnimation:group forKey:nil];

UIView和核心动画区别

  • 核心动画一切都是假象,并不会真实的改变图层的属性值;UIView动画必须通过修改属性的真实值,才有动画效果。如果以后做动画的时候,不需要与用户交互,通常用核心动画(转场)。
    CABasicAnimation *anim = [CABasicAnimation animation];    anim.keyPath = @"position";    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(150, 400)];    //注意取消反弹必须放在图层添加动画之前    anim.removedOnCompletion = NO;    anim.fillMode = kCAFillModeForwards;    anim.delegate = self;    [_imageview.layer addAnimation:anim forKey:nil];

在动画完成的代理中打印_imageview.layer.position,打印结果为{165, 114.5},说明_imageview.layer.position并没有发生改变

    [UIView animateWithDuration:0.5 animations:^{        _imageview.layer.position = CGPointMake(150, 400);    } completion:^(BOOL finished) {        NSLog(@"%@",NSStringFromCGPoint(_imageview.layer.position));    }];

打印结果为{150, 400}

其他

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