图形上下文栈保存的仅仅是当前的绘图状态信息也就是线宽,颜色,缩放,平移啊这些信息,跟路径和输出目标都是没有关系的。
图形上下文栈有两个操作一个是void CGContextSaveGState(CGContextRef c)这个函数就是将当前绘图信息的状态保存到一个context的 graphics state栈中。关于state的值,如下所示
CTM (current transformation matrix)
clip region
image interpolation quality
line width
line join
miter limit
line cap
line dash
flatness
should anti-alias
rendering intent
fill color space
stroke color space
fill color
stroke color
alpha value
font
font size
character spacing
text drawing mode
shadow parameters
the pattern phase
the font smoothing parameter
blend mode
还有个是 void CGContextRestoreGState(CGContextRef c)将栈顶的绘图状态出栈,替换掉现在的图形上下文的绘图状态。代码如下所示可以很好的诠释了这个操作。
//1、获取上下文
CGContextRef ctx=UIGraphicsGetCurrentContext();
//进行备份这个绘图状态
CGContextSaveGState(ctx);
//根据所设置的路径画弧,参数:x,y为圆点坐标,radius半径,startAngle为开始的弧度,endAngle为 结束的弧度,clockwise 0为顺时针,1为逆时针
CGContextAddArc(ctx, 150,150 , 100, 0, 2*M_PI, 1);
CGContextMoveToPoint(ctx, 0, 0);
CGContextAddLineToPoint(ctx, 300, 300);
//设置下线宽
CGContextSetLineWidth(ctx, 10);
CGContextSaveGState(ctx);//这里又备份了一次这次备份的就是10个线宽的那个状态了如果我们下面只有一个恢复状态那就是我这个保存的状态,
如果有两个还是第一个我们保存的状态
//设置颜色
[[UIColor greenColor]set];
//渲染
CGContextStrokePath(ctx);
//拼接下路径
CGContextMoveToPoint(ctx, 30, 30);
CGContextAddLineToPoint(ctx, 100, 30);
//恢复最上面保存的那个状态,只要在最下面那个渲染之前用就可以了,如果不恢复状态上下文的状态还是我们上面设置颜色和线宽的那个状态
CGContextRestoreGState(ctx);
CGContextRestoreGState(ctx);
//渲染
CGContextStrokePath(ctx);
在最后三行代码中如果我们注释掉一个CGContextRestoreGState,那么会出现这样的情况,中间的那个黑线就是线宽为10的情况
如果不注释掉就是下图所示那样的