iOS quartzCore 学习之CALayer02

一、自定义层的方法1

方法:

1> 创建一个CALayer的子类

@interface MyLayer : CALayer

2>然后覆盖drawInContext方法,使用Quartz2D API 进行绘制

- (void)drawInContext:(CGContextRef)ctx{
    // 设置颜色
    CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
    // 设置起点
    CGContextMoveToPoint(ctx, 50, 50);
    // 连线
    CGContextAddLineToPoint(ctx, 100, 100);
    
    CGContextAddLineToPoint(ctx, 0, 100);
    // 合并路径
    CGContextClosePath(ctx);
    // 绘制路径
    CGContextFillPath(ctx);
}

3> 创建layer

 MyLayer* layer = [MyLayer layer];
    layer.bounds = CGRectMake(50, 50, 150, 150);
    layer.position = CGPointMake(100, 100);
    
    // 绘制图层 ,需要调用setNeedsDisplay这个方法,才会触发drawInContext:方法的调用,然后进行绘图
    [layer setNeedsDisplay];
    [self.view.layer addSublayer:layer];

二、自定义层的方法2

方法描述:设置CALayer的delegate,然后让delegate实现drawLayer:inContext:方法,当CALayer需要绘图时,会调用delegate的drawLayer:inContext:方法进行绘图。

* 这里要注意的是:不能再将某个UIView设置为CALayer的delegate,因为UIView对象已经是它内部根层的delegate,再次设置为其他层的delegate就会出问题。UIView和它内部CALayer的默认关系图:

1.创建新的层,设置delegate,然后添加到控制器的view的layer中

   CALayer* layer = [CALayer layer];
    layer.bounds = CGRectMake(0, 0, 150, 150);
    layer.position = CGPointMake(100, 100);
    layer.delegate = self;
    [layer setNeedsDisplay];
    [self.view.layer addSublayer:layer];

  2.实现代理方法

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
    CGContextSetLineWidth(ctx, 5);
//    CGContextFillRect(ctx, CGRectMake(10, 10, 50, 50));
    CGContextStrokeRect(ctx, CGRectMake(10, 10, 50, 50));
}

  三、总结

无论采取哪种方法来自定义层,都必须调用CALayer的setNeedsDisplay方法才能正常绘图。

* 当UIView需要显示时,它内部的层会准备好一个CGContextRef(图形上下文),然后调用delegate(这里就是UIView)的drawLayer:inContext:方法,并且传入已经准备好的CGContextRef对象。而UIView在drawLayer:inContext:方法中又会调用自己的drawRect:方法

* 平时在drawRect:中通过UIGraphicsGetCurrentContext()获取的就是由层传入的CGContextRef对象,在drawRect:中完成的所有绘图都会填入层的CGContextRef中,然后被拷贝至屏幕

 

转载于:https://www.cnblogs.com/16zj/p/6377988.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值