UILabel method of DrawDrect

First, the problem

  If you inherit a UILabel achieve their Label, and the blank in DrawRect method subclass, nothing to write, what will happen?

  code show as below:

  YOU

@interface ViewController ()

@property (nonatomic, strong) DrawTestLabel *dwLabel;

@end

@implementation ViewController

- (DrawTestLabel *)dwLabel
{
    if(!_dwLabel) {
        _dwLabel = [[DrawTestLabel alloc] init];
        _dwLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return _dwLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[self view] setBackgroundColor:[UIColor greenColor]];
    [[self dwLabel] setFrame:CGRectMake(0, 0, 200, 50)];
    [[self view] addSubview:[self dwLabel]];
    [[self dwLabel] setText:@"Hello"];
    [[self dwLabel] setCenter:[self view].center];
}


@end

  Label

@implementation DrawTestLabel


- (void)drawRect:(CGRect)rect {
    // Drawing code
//    [super drawRect:rect];
}


@end

  Note After adjusting DrawRect call the parent class method, you will find nothing above the screen

  After opening the Xcode debugger, you will find there is a transparent layer

  

 

Second, the problem analysis

  We know that the relationship between UIView and Layer, Layer responsible for screen rendering, UIVIew responsible for incident response;

  In the drawing picture CALayer be achieved by implementing CALayerDelegate, it is usually a layer of delegate UIView itself.

  CALayerDelegate method drawlayer: incontext method each time drawing, calls the UIView Drawrect method, under UIView implements the method DrawRect.

  

  

  Then above their inheritance UILbel, after rewriting Drawrect method, substantially as logic

  1, CALayer receive a callback system, start rendering

  2, the system finds layer (Label) implements Drawrect method, then creates a transparent canvas, the size of UILabel are made smaller, scale is the scale of the screen

  3, by calling Drawrect delegate method, draw something on the canvas

  4, the new UILabel TextKit (the bottom is about CoreText) drawn by the text onto the canvas, this period is done on the CPU

  5, draw completed bitmap, again Runloop cycle, will be unified renderserver submitted to the background by the system

  6、render server进程处理不同的图层,通过操作GPU进行叠加渲染操作

  

  为什么Drawrect消耗比较高?

  因为绘制在CPU上面操作

  绘制完成的bitmap,会通过跨进城IPC传递给render server存在系统调用消耗

  render 传递内存中的bitmap到GPU的缓存上面生成纹理 ,再次产生消耗

 

  普通的UIView通过设置属性的方式,不涉及到传递大块内存的操作,这些类似背景色、透明度、都是通过renderserver来完成的,GPU操作效率会比较高。

  

  

Guess you like

Origin www.cnblogs.com/doudouyoutang/p/11027869.html