iOS高级动画之Layer与隐式动画详解

一、相关知识点

1.官方架构

  • Graphics Hardware可以理解为GPU
  • Metal、Core Graphics是对GPU的操作,由C语言封装
  • Core Animation操作Metal、Core Graphics
  • UIKit iOS UI框架
  • AppKit相当于 Mac OS 的 UIKit
A30B46DB-8E85-4745-BA47-C392D65ABA6E.png

2.Core Animation

  • Core Animation 并不是单独的框架,他位于 QuartzCore
  • Core Animation 包含了 CAAnimation
coraanimation.png

3.UIView和CALayer

  • UIView 继承于 UIResponderNSObject
  • CALayer 继承与 NSObject
  • UIView 响应事件
  • CALayer 显示内容

4.CALayer的存在意义?

  • 由于Mac OSiOS 在键鼠操作与多点触控上有本质区别,所以在渲染层 *CALayer} 单独封装出来。
  • 这也就是为什么 iOSUIKitUIViewMac OSAppKitNSView 的原因

5. CALayer的属性AnchorPoint

  • AnchorPoint 锚点 默认值为 (0.5,0.5)
  • 锚点是单位坐标取值区间 [0,1]
5.1验证AnchorPoint的变化是否与Position有关
  • 5.1.1试验AnchorPoint {1,1}
    subViewOne = [[UIView alloc] initWithFrame:CGRectMake(100.f, 100.f, 100.f, 100.f)];
    subViewOne.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:subViewOne];

    subView = [[EOCViewOne alloc] init];
    subView.frame = CGRectMake(100.f, 100.f, 100.f, 100.f);
    subView.layer.anchorPoint = CGPointMake(1, 1);
    subView.backgroundColor = [UIColor redColor];
    [self.view addSubview:subView];
    
    NSLog(@"position %@", NSStringFromCGPoint(subView.layer.position));

4B7EA3B7-0937-4347-BC75-F4AA2D86222A.png

NSLog : position {150,150}

  • 5.1.2试验AnchorPoint {0,0}
    subViewOne = [[UIView alloc] initWithFrame:CGRectMake(100.f, 100.f, 100.f, 100.f)];
    subViewOne.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:subViewOne];

    subView = [[EOCViewOne alloc] init];
    subView.frame = CGRectMake(100.f, 100.f, 100.f, 100.f);
    subView.layer.anchorPoint = CGPointMake(1, 1);
    subView.backgroundColor = [UIColor redColor];
    [self.view addSubview:subView];
    
    NSLog(@"position %@", NSStringFromCGPoint(subView.layer.position));

anchorpoint2.png

NSLog : position {150,150}

  • 5.1.3 结论
- AnchorPoint 的改变与 position 无关,但是frame改变了
- AnchorPoint的 位置 就是 position的位置
- position 是 AnchorPoint 在父view上的位置
- frema 本质是根据 position、bouns、AnchorPoint计算出来的
- 我要钉一副画(bouns)到到墙上,那么我这个钉子钉的位置就是 position 
- 先改变AnchorPoint在图形上的位置,再让图形随着AnchorPoint,把AnchorPoint放到position的位置
  • 5.1.4 拓展思考
    如果我们先修改 AnchorPoint 再设置 frame,会怎么样呢?
  subView.layer.anchorPoint = CGPointMake(1, 1);
  subView.frame = CGRectMake(100.f, 100.f, 100.f, 100.f);
    
//两个view重合,anchorPoint改变,position因frame而改变
//position {200,200} ; anchorPoint {1,1}
position.png
  • 5.1.5 AnchorPoint、frame、position的推导公式
frame.origin.x = position.x - anchorPoint.x * bouns.size.width
frame.origin.y = position.x - anchorPoint.y * bouns.size.height

6.transform后的frame神奇变化

  • 我们旋转45度
subView.transform = CGAffineTransformMakeRotation(M_PI_2/2);
transform.png
- frame 改变
- frame 为白色区域
- frame 不等于bouns

7. AnchorPoint与动画的结合使用

  • 通过改变锚点位置,结合NSTimer,制作时钟动画
clock.png

8.Layer.content

8.1 直接设置content
  • LayerView的核心内容,ViewLayer 的代理
  • 先给一个结论,UIImageView 是通过 UIViewLayer.content实现,在这里 content 是一个位图指针:
//_uiview 为 (UIView *)类型
_uiview = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    _uiview.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"1.png"].CGImage);
    [self.view addSubview:_uiview];
(lldb) po _uiview
<UIView: 0x7fdd7c637e80; frame = (100 100; 100 100); layer = <CALayer: 0x6000002327c0>>

(lldb) po _uiview.layer.contents
<CGImage 0x6000001c2df0>
    <<CGColorSpace 0x60000002a220> (kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Generic Gray Gamma 2.2 Profile)>
        width = 81, height = 65, bpc = 8, bpp = 16, row bytes = 162 
        kCGImageAlphaLast | 0 (default byte order) 
        is mask? No, has mask? No, has matte? No, should interpolate? Yes
8.2 添加一个subLayer.content
  • 必须要调用setNeedsDisplay才会触发代理方法- (void)displayLayer:(CALayer *)layer- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
  • 如果- (void)displayLayer:(CALayer *)layer 和同时存在只会触发- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
  • UIView的drawRect本质就是通过layer的代理方法- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx来调用的
  • 实例代码:
    imgLayer = [CALayer layer];
    imgLayer.frame = CGRectMake(100.f, 100.f, 100.f, 100.f);
   // imgLayer.contents = (__bridge id)[UIImage imageNamed:@"bubble.png"].CGImage;
    imgLayer.delegate = self;
    [self.view.layer addSublayer:imgLayer];
    
    [imgLayer setNeedsDisplay];//必须要调用这个才会出发代理
- (void)displayLayer:(CALayer *)layer {
    //写了此代理方法就不会执行下面的代理方法
    imgLayer.contents = (__bridge id)[UIImage imageNamed:@"1.png"].CGImage;
    NSLog(@"displayLayer");
    
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    //UIView的drawRect本质就通过此代理方法调用
    NSLog(@"drawLayer");
    
}
  • 堆栈调用详情:
stack2.png

9.layer的delegate不可随意设置

9.1 一种难以追踪的crush情况
  • 在UIView里自定义的layer变量的delegate不能设置为UIView自身
  • 原理是因为(UIView *) self.layer.delegate = self; 如果其他layer.delegate = self 会产生素乱,UIView无法判断让哪个layer遵循代理的方法
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
       
        _delegate = [[EOCLayerDelegate alloc] init];
        CALayer *layer = [CALayer layer];
        layer.delegate = self; //设置此行代码crush
        layer.backgroundColor = [UIColor redColor].CGColor;
        [self.layer addSublayer:layer];
        
    }
    
    return self;
}
9.2 解决办法
  • 重写一个遵循<CAAnimationDelegate>的类,让子layer的delegate设置为这个类
@interface EOCLayerDelegate : NSObject<CAAnimationDelegate>

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;

@end

@implementation EOCLayerDelegate

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    
    NSLog(@"drawLayer2222");
    
}

@end
@interface EOCView () {
    EOCLayerDelegate *_delegate ;
}
@end

@implementation EOCView
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
       
        _delegate = [[EOCLayerDelegate alloc] init];
        CALayer *layer = [CALayer layer];
        layer.delegate = (id)_delegate;
        layer.backgroundColor = [UIColor redColor].CGColor;
        [self.layer addSublayer:layer];
        
    }
    
    return self;
}
9.3 由 9.2 解决方案引起的并发crush
  • 经过排除发现添加的子layer在 Controller 的 dealloc 不会释放,所以我们必要手动 remove 处理
- (void)dealloc {
    
    [imgLayer removeFromSuperlayer];
    
}

10. layer遮罩层

  • 先上一张底图,我们在上面做 两种 mask特效
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100.f, 100.f, 200.f, 200.f)];
    imageView.image = [UIImage imageNamed:@"bg-mine.png"];
    [self.view addSubview:imageView];
  • 背景图:
bg.png
  • mask图:
mask.png
  • 为背景图添加遮罩效果
    UIImage *imageTwo = [UIImage imageNamed:@"bubble.png"];
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = imageView.bounds;
    imageLayer.contents = (__bridge id)imageTwo.CGImage;   
    imageView.layer.mask = imageLayer;
  • 添加mask后的效果:
mask1.png
  • 设置mask的显示区域
imageLayer.contentsCenter = CGRectMake(0.5f, 0.5, 0.1, 0.1);
mask2.png

Layer Animation

1. 隐式动画效果展示

  • layer层有隐式动画(默认自动调用的动画效果)
  • 我们通过切换layer层的背景颜色来验证
  • 结论:每次切换颜色都有一个渐变的动画效果,在UIView是不会触发这种效果的
  • 同理,我们改变layer.bouns也会带有隐式动画的效果
     //layer层有隐式动画
    eocLayer = [EOCLayer layer];
    eocLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    eocLayer.frame = CGRectMake(100.f, 100.f, 100.f, 100.f);
    [self.view.layer addSublayer:eocLayer];
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        eocLayer.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256.f)/255.f green:arc4random_uniform(256.f)/255.f blue:arc4random_uniform(256.f)/255.f alpha:1.f].CGColor;
}

2. 隐式动画的底层实现

  • 核心方法+ (nullable id<CAAction>)defaultActionForKey:(NSString *)event;
code.png
1. 如果我们设置了layer的代理,那么会去方法 -actionForLayer:forKey; 寻找key值,根据key来确定要执行的action(动画)
 - 1.1 如果 -(id<CAAction>)actionForLayer:forKey;  返回的是非nil包括 [NSNull null]), 停止 ; nil继续下一个步骤
 - 1.2 由于 actionForLayer 是CAAction的代理方法,选择写在Controller下,也可在UIView.m下用于开启隐式动画

2. 从layer的 `action` 字典里面搜索key
3. 从layer的 `style` 字典里面搜索key
4. 根据方法 +defaultActionForKey: 看他的返回值
5.如果以上步骤都没有结果,那么调用方法 -actionForKey,返回一个默认的动画,如<CABasicAnimation>
6. -addAnimation 就会把这个动画添加到layer上

 * If any of these steps results in a non-nil action object, the
 * following steps are ignored.
 *如果上述的步骤返回一个非nil的结果,那么当前步骤就被
 *停止了 (不包含步骤5.6. 步骤根据nil或者非nil决定最后的动画)

  • 所以通过了解了隐式动画的底层执行步骤,我们可以实现狸猫换太子的方式替换隐式动画
  • 我可以选择在 -actionForKey 或者 -addAnimation 中重写一个隐式动画
- (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key {
    
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.duration = 1.f;
    animation.fromValue = (__bridge id)[UIColor blackColor].CGColor;
    animation.toValue = (__bridge id)[UIColor redColor].CGColor;
    
    [super addAnimation:animation forKey:key]; //最后执行的动画以此处为准
    
}

- (id<CAAction>)actionForKey:(NSString *)event {
    
    NSLog(@"actionForKey %@ action %@", event, [super actionForKey:event]);
    
     CABasicAnimation *animation = [CABasicAnimation animation];
    animation.duration = 3.f;
    animation.fromValue = (__bridge id)[UIColor whiteColor].CGColor;
    animation.toValue = (__bridge id)[UIColor greenColor].CGColor;
    
    return animation; 
    //将此animation传递给 -addAnimation
    //如果传递nil,在 -addAnimation中也没有自定义动画,那么layer就不会执行隐式动画
    
}

3. 为什么UIView没有隐式动画?

  • 通过上面的探索,我在UIView.m下,在-actionForLayer:forKey中返回nil,那么改变 UIView 的backgroundColor,UIView 也实现了隐式动画
  • 结论:苹果在 UIView 中,让 -actionForLayer:forKey 的返回值为 [NSNull null] 导致了 UIView 失去了隐式动画的效果
  • 同理: [UIView animation] 也是对 layer 隐式动画代理的操作

事务

  • 事务可以影响动画,比如动画的时间
  • 通常在默认的动画模式下才生效,如果在layer的代理方法里设置过动画,则以代理的动画设置为准
  • 代理可以用于取消action,从而达到关闭动画的效果
 //事务
    [CATransaction begin];
    [CATransaction setAnimationDuration:5.f]; //重置动画时间
//    [CATransaction setDisableActions:YES]; //action无效化,即关闭动画

         //animation code area

    [CATransaction commit];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,321评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,001评论 5 13
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。 1.UIView...
    请叫我周小帅阅读 3,000评论 1 23
  • Core Animation Core Animation,中文翻译为核心动画,它是一组非常强大的动画处理API,...
    45b645c5912e阅读 2,968评论 0 21
  • 前言 本文只要描述了iOS中的Core Animation(核心动画:隐式动画、显示动画)、贝塞尔曲线、UIVie...
    GitHubPorter阅读 3,538评论 7 11