国内顶尖网站设计公司,信息无障碍 网站建设,大连网站搜索优,中国做民宿的网站本文目录 一、自定义层的方法1二、自定义层的方法2 三、其他 自定义层#xff0c;其实就是在层上绘图#xff0c;一共有2种方法#xff0c;下面详细介绍一下。 回到顶部一、自定义层的方法1 方法描述#xff1a;创建一个CALayer的子类#xff0c;然后覆盖drawInContext:方… 本文目录 一、自定义层的方法1二、自定义层的方法2 三、其他 自定义层其实就是在层上绘图一共有2种方法下面详细介绍一下。 回到顶部一、自定义层的方法1 方法描述创建一个CALayer的子类然后覆盖drawInContext:方法使用Quartz2D API进行绘图 1.创建一个CALayer的子类 2.在.m文件中覆盖drawInContext:方法在里面绘图 1 implementation MJLayer2 3 #pragma mark 绘制一个实心三角形4 - (void)drawInContext:(CGContextRef)ctx {5 // 设置为蓝色6 CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);7 8 9 // 设置起点
10 CGContextMoveToPoint(ctx, 50, 0);
11 // 从(50, 0)连线到(0, 100)
12 CGContextAddLineToPoint(ctx, 0, 100);
13 // 从(0, 100)连线到(100, 100)
14 CGContextAddLineToPoint(ctx, 100, 100);
15 // 合并路径连接起点和终点
16 CGContextClosePath(ctx);
17
18 // 绘制路径
19 CGContextFillPath(ctx);
20 }
21
22 end 3.在控制器中添加图层到屏幕上 1 MJLayer *layer [MJLayer layer];
2 // 设置层的宽高
3 layer.bounds CGRectMake(0, 0, 100, 100);
4 // 设置层的位置
5 layer.position CGPointMake(100, 100);
6 // 开始绘制图层
7 [layer setNeedsDisplay];
8 [self.view.layer addSublayer:layer]; 注意第7行需要调用setNeedsDisplay这个方法才会触发drawInContext:方法的调用然后进行绘图 回到顶部二、自定义层的方法2 方法描述设置CALayer的delegate然后让delegate实现drawLayer:inContext:方法当CALayer需要绘图时会调用delegate的drawLayer:inContext:方法进行绘图。 * 这里要注意的是不能再将某个UIView设置为CALayer的delegate因为UIView对象已经是它内部根层的delegate再次设置为其他层的delegate就会出问题。UIView和它内部CALayer的默认关系图 1.创建新的层设置delegate然后添加到控制器的view的layer中 1 CALayer *layer [CALayer layer];2 // 设置delegate3 layer.delegate self;4 // 设置层的宽高5 layer.bounds CGRectMake(0, 0, 100, 100);6 // 设置层的位置7 layer.position CGPointMake(100, 100);8 // 开始绘制图层9 [layer setNeedsDisplay];
10 [self.view.layer addSublayer:layer]; * 在第3行设置了CALayer的delegate这里的self是指控制器 * 注意第9行需要调用setNeedsDisplay这个方法才会通知delegate进行绘图 2.让CALayer的delegate(前面设置的是控制器)实现drawLayer:inContext:方法 1 #pragma mark 画一个矩形框2 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {3 // 设置蓝色4 CGContextSetRGBStrokeColor(ctx, 0, 0, 1, 1);5 // 设置边框宽度6 CGContextSetLineWidth(ctx, 10);7 8 // 添加一个跟层一样大的矩形到路径中9 CGContextAddRect(ctx, layer.bounds);
10
11 // 绘制路径
12 CGContextStrokePath(ctx);
13 } 回到顶部三、其他 1.总结 无论采取哪种方法来自定义层都必须调用CALayer的setNeedsDisplay方法才能正常绘图。 2.UIView的详细显示过程 * 当UIView需要显示时它内部的层会准备好一个CGContextRef(图形上下文)然后调用delegate(这里就是UIView)的drawLayer:inContext:方法并且传入已经准备好的CGContextRef对象。而UIView在drawLayer:inContext:方法中又会调用自己的drawRect:方法 * 平时在drawRect:中通过UIGraphicsGetCurrentContext()获取的就是由层传入的CGContextRef对象在drawRect:中完成的所有绘图都会填入层的CGContextRef中然后被拷贝至屏幕