记录一次Quartz2D学习(一)

时间:2023-11-10 13:19:32

经常看点

drawRect的重写  但是不知道这究竟是神马

今天开始学习这一块的东西,更确切地说是深入

早在view的时候 就经常会调用layer的maskToBounds属性,其实 重写

drawRect方法  也就是对layer的一个绘制

重写也比较简单

1 线条

1.1 下面就是简单地线条的画法:(效果如图)

- (void)drawRect:(CGRect)rect {

// Drawing code

//获取绘制图形的上下文

CGContextRef    ctx =UIGraphicsGetCurrentContext();

//设置线条的宽度

CGContextSetLineWidth(ctx, 20);

//设置线条的填充颜色

CGContextSetRGBStrokeColor(ctx, 250, 250, 250, 0.5);

//设置线条的起点

CGContextMoveToPoint(ctx, 100, 100);

//添加线条

CGContextAddLineToPoint(ctx, 150, 150);

//设置线条的圆角

CGContextSetLineCap(ctx, kCGLineCapRound);//kCGLineCapRound 属性有多种,可以设置线条的各种边角状态

//进行绘制

CGContextStrokePath(ctx);

}

记录一次Quartz2D学习(一)

1.2 一笔画两条线段

方法重写如下:

- (void)drawRect:(CGRect)rect {

CGContextRef    ctx =UIGraphicsGetCurrentContext();

CGContextSetLineWidth(ctx, 20);

CGContextSetRGBStrokeColor(ctx, 250, 250, 250, 0.5);

CGContextMoveToPoint(ctx, 100, 100);

CGContextAddLineToPoint(ctx, 150, 150);

CGContextSetLineCap(ctx, kCGLineCapRound);

CGContextSetLineJoin(ctx, kCGLineJoinRound);

//这两句是在此前的基础上添加的

//先移动到对应的点,再进行绘制

CGContextMoveToPoint(ctx, 150, 150);//可有可无 , 没有这句,效果相同

CGContextAddLineToPoint(ctx, 100, 200);

CGContextStrokePath(ctx);

}

记录一次Quartz2D学习(一)

1.3 绘制状态的保存问题 :

当你保存了绘制的状态 之后,就可以回复到上一次保存的状态

TIP: 保存与恢复方法,要成对出现,否则会出现报错---原因,栈内不存在绘制状态

重写方法如下

- (void)drawRect:(CGRect)rect {

CGContextRef    ctx =UIGraphicsGetCurrentContext();

//保存当前的绘制状态

CGContextSaveGState(ctx);

CGContextSetLineWidth(ctx, 20);

CGContextSetRGBStrokeColor(ctx, 250, 250, 250, 0.5);

CGContextMoveToPoint(ctx, 100, 100);

CGContextAddLineToPoint(ctx, 150, 150);

CGContextSetLineCap(ctx, kCGLineCapRound);

CGContextSetLineJoin(ctx, kCGLineJoinRound);

//提取出上一次保存的绘制状态

CGContextRestoreGState(ctx);

//另外一种颜色的设置方法

[[UIColor yellowColor] set];

CGContextMoveToPoint(ctx, 150, 150);//可有可无 , 没有这句,效果相同

CGContextAddLineToPoint(ctx, 100, 200);

CGContextStrokePath(ctx);

}

记录一次Quartz2D学习(一)