CALayer绘制流程

关系

UIView是如何显示一个页面的?

  1. CALayer通过代理,将需要绘制的信息传递给UIView
  2. UIView通过CoreGraphics进行绘制的操作;
  3. 绘制好的内容交给CALayer,方法有两种:
  • layer.contents = image
  • 存储在CABackingStore
  1. 通过OpenGL ES/Metal(GPU)进行显示。
  • CALayer的调用流程

CALayer调用流程,分为布局绘制两部分。

  1. 布局部分,先会调用CALayerlayerSublayers方法,再调用viewlayoutSubViews
  2. 绘制部分,通过设置layersetNeedsDisplay标记需要刷新,然后调用CALayerdisplay方法,再判断UIViewdisplayLayer方法是否实现,如果实现走自定义绘制流程,否则进入系统绘制流程,会先创建buffercontext,然后调用drawLayer:InContext:,再执行UIViewdrawRect
流程
  1. 通过在drawRect进行断点,查看函数调用栈:
 * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
 * frame #0: 0x0000000103de7317 CALayerProcessDemo`-[LCustomLayerView drawRect:](self=0x00007ff154508f80, _cmd="drawRect:", rect=(origin = (x = 0, y = 0), size = (width = 200, height = 200))) at LCustomLayerView.m:13:5
 frame #1: 0x00000001083704d3 UIKitCore`-[UIView(CALayerDelegate) drawLayer:inContext:] + 550  //默认调取
 frame #2: 0x00000001098f393d QuartzCore`-[CALayer drawInContext:] + 285
 frame #3: 0x00000001097ee969 QuartzCore`CABackingStoreUpdate_ + 173 //后台存储区
 frame #4: 0x00000001098fa3fc QuartzCore`___ZN2CA5Layer8display_Ev_block_invoke + 44
 frame #5: 0x00000001098f3439 QuartzCore`-[CALayer _display] + 2443  //绘制
 frame #6: 0x0000000109904e77 QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 359
 frame #7: 0x000000010987424a QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 328
 frame #8: 0x00000001098ab606 QuartzCore`CA::Transaction::commit() + 610
 frame #9: 0x0000000107eab2c3 UIKitCore`__34-[UIApplication _firstCommitBlock]_block_invoke_2 + 128
 frame #10: 0x0000000105081cbc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
 frame #11: 0x0000000105081480 CoreFoundation`__CFRunLoopDoBlocks + 336
 frame #12: 0x000000010507bd04 CoreFoundation`__CFRunLoopRun + 1252
 frame #13: 0x000000010507b4d2 CoreFoundation`CFRunLoopRunSpecific + 626
 frame #14: 0x000000010d6bf2fe GraphicsServices`GSEventRunModal + 65
 frame #15: 0x0000000107e91fc2 UIKitCore`UIApplicationMain + 140
 frame #16: 0x0000000103de76a0 CALayerProcessDemo`main(argc=1, argv=0x00007ffeebe17ea8) at main.m:14:16
 frame #17: 0x0000000106a00541 libdyld.dylib`start + 1
 frame #18: 0x0000000106a00541 libdyld.dylib`start + 1
  1. 从调用栈中可以看到在调用drawRect之前,还会调用-[CALayer _display](视图绘制)、-[CALayer drawInContext:](默认调用)、-[UIView(CALayerDelegate) drawLayer:inContext:](自定义绘制流程)等方法,我们试着实现drawLayer:inContext时,发现drawRect不会再走。

下面我们通过自定义CALayer,来分析下系统的CALayer到底做了什么:

@protocol LLayerDelegate 

- (void)l_layoutSublayersOfLayer:(CALayer *)layer;
- (void)l_displayLayer:(CALayer *)layer;
- (void)l_drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;

- (CGContextRef)l_beginDraw;
- (void)l_endDraw;

@end
@interface LLayer : CALayer

@end
@implementation LLayer
- (void)layoutSublayers { //这个会调用UIView layoutSubviews
    __strong id  delegate = (id)self.delegate;
    if ([delegate respondsToSelector:@selector(l_layoutSublayersOfLayer:)]) {
        //调用代理的实现
    }
}

- (void)display {
    //询问代理绘制
    __strong id  delegate = (id)self.delegate;
    CGContextRef context = [delegate l_beginDraw];
    //如何绘制
    [delegate l_drawLayer:self inContext:context];
        
    [delegate l_displayLayer:self];
        
    [delegate l_endDraw];
}
@end
@interface LCustomLayerView()
@end

@implementation LCustomLayerView
//下面我们模拟下layer的执行流程
//layer走自定义的
+ (Class)layerClass {
    return [LLayer class];
}

#pragma -mark LLayerDelegate
- (void)l_layoutSublayersOfLayer:(CALayer *)layer {
    [self layoutSubviews];
}

- (CGContextRef)l_beginDraw {
    //开始绘制,并返回context
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.layer.opaque, self.layer.contentsScale);
    CGContextRef cRef = UIGraphicsGetCurrentContext();
    return cRef;
}

- (void)l_drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    [[UIColor blueColor] set];
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(self.bounds.size.width/2.0 - 30, self.bounds.size.height/2.0 - 30, 60, 60)];
    CGContextAddPath(ctx, path.CGPath);
    CGContextFillPath(ctx);
}

//自定义绘制
- (void)l_displayLayer:(CALayer *)layer {
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    dispatch_async(dispatch_get_main_queue(), ^{
        layer.contents = (__bridge id _Nullable)(img.CGImage);
    });
}

- (void)l_endDraw {
    UIGraphicsEndImageContext();
}

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.clView];
}
- (LCustomLayerView *)clView {
    if (!_clView) {
        _clView = [LCustomLayerView new];
        _clView.frame = CGRectMake(50, 100, 200, 200);
        _clView.backgroundColor = [UIColor orangeColor];
    }
    return _clView;
}

@end
  • 补充
  1. 重新布局方法,layoutSubviews调用时机:
  • 延时执行
    • 被添加到父视图中
    • 添加子控件
    • 尺寸发生变化
    • 子控件尺寸发生变化
    • 滚动UIScrollView
    • 旋转屏幕
    • setNeedsLayout,且有布局需要更新
  • 立即执行
    • 调用layoutIfNeeded时且有变化会立即触发
  1. 重新绘制方法,drawRect调用时机
  • loadViewviewDidLoad方法之后调用
  • View初始化时没有设置rect大小,将直接导致drawRect不会被调用
  • 在调用sizeThatFits后被调用,可以先调用sizeToFit计算出size,然后系统自动调用drawRect
  • 通过设置contentModeUIViewContentModeRedraw,每次设置或更改frame的时候自动调用drawRect
  • rect不为0,调用setNeedsDisplaysetNeedsDisplayInRect会触发

{\large\text{作者:lmfei 链接:https://www.jianshu.com/p/f05b8f1d27f2 来源: 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。}}

你可能感兴趣的:(CALayer绘制流程)