view的完整显示过程:
1.view.layer会准备一个Layer Graphics Context(图层类型上下文)
2.调用view.layer.delegate(即view)的drawLayer:inContext:并传入准备好的上下文
3.view的drawLayer:inContext:方法内部会调用view的drawRect:方法
4.view就可以在drawRect:方法中实现绘图,所有东西都会绘制到view.layer上
5.系统再将view.layer内容拷贝到屏幕上,完成显示
1 // 2 // ViewController.m 3 // calayer,自定义Layer 4 // 5 // Created by ys on 15/11/21. 6 // Copyright (c) 2015年 ys. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "ysLayer.h" 11 /** 12 * ysLayer.h及.m文件内容 13 14 #import <QuartzCore/QuartzCore.h> 15 @interface ysLayer : CALayer 16 @end 17 18 #import "ysLayer.h" 19 @implementation ysLayer 20 -(void)drawInContext:(CGContextRef)ctx 21 { 22 CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50)); 23 CGContextSetRGBFillColor(ctx, 0, 0, 1, 1.0); 24 CGContextFillPath(ctx); 25 } 26 27 @end 28 */ 29 30 31 @interface ViewController () 32 33 @end 34 35 @implementation ViewController 36 37 - (void)viewDidLoad { 38 [super viewDidLoad]; 39 [self diyLayer2]; 40 [self diyLayer1]; 41 } 42 43 -(BOOL)prefersStatusBarHidden 44 { 45 return YES; 46 } 47 48 49 -(void)diyLayer1 50 { 51 ysLayer *layer = [[ysLayer alloc]init]; 52 layer.backgroundColor = [UIColor redColor].CGColor; 53 layer.bounds = CGRectMake(0, 0, 200, 200); 54 layer.anchorPoint = CGPointMake(0, 0); 55 [self.view.layer addSublayer:layer]; 56 [layer setNeedsDisplay]; 57 } 58 59 60 -(void)diyLayer2 61 { 62 CALayer *layer = [[CALayer alloc]init]; 63 layer.backgroundColor = [UIColor blackColor].CGColor; 64 layer.bounds = CGRectMake(0, 0, 200, 200); 65 layer.position = CGPointMake(0, 200); 66 layer.anchorPoint = CGPointZero; 67 layer.delegate = self;//继承自NSObject的类都可以作为Layer的代理 68 [self.view.layer addSublayer:layer]; 69 [layer setNeedsDisplay]; 70 } 71 72 //代理方法 73 -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 74 { 75 CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 50, 50)); 76 CGContextSetRGBFillColor(ctx, 1, 0, 0, 1); 77 CGContextFillPath(ctx); 78 } 79 80 @end
时间: 2024-10-22 16:54:48