源码下载地址:http://download.youkuaiyun.com/detail/liu537192/8513887
这里先上核心代码:
//
// JLView.m
// 02-图形上下文栈
//
// Created by XinYou on 15-3-19.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import "JLView.h"
@implementation JLView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// [self drawLine_1];
[self drawLine_2];
}
- (void)drawLine_2{
// 1,获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2,将ctx拷贝一份放到上下文栈中
CGContextSaveGState(ctx);
// 3,设置绘图状态
// 设置线宽
CGContextSetLineWidth(ctx, 10);
// 设置颜色
[[UIColor redColor] set];
// 4,画第1根线
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 200, 200);
CGContextStrokePath(ctx);
// 5,还原ctx
CGContextRestoreGState(ctx);
// 6,画第2根线
CGContextMoveToPoint(ctx, 100, 250);
CGContextAddLineToPoint(ctx, 250, 250);
CGContextStrokePath(ctx);
}
- (void)drawLine_1{
// 1,获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2,设置绘图的状态
// 设置线宽
CGContextSetLineWidth(ctx, 10);
// 设置颜色
[[UIColor redColor] set];
// 3,画线
// 第1根线
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 200, 200);
CGContextStrokePath(ctx);
// 第2根线
CGContextMoveToPoint(ctx, 100, 250);
CGContextAddLineToPoint(ctx, 250, 250);
CGContextStrokePath(ctx);
}
@end
drawLine_1的效果图如图1所示,drawLine_2的效果图如图2所示。为什么会这样呢?
1,drawLine_2中的第2步,我们将ctx拷贝了一份放到上下文栈中(我们暂且叫它ctx_copy)。
2,drawLine_2中的第3步,设置绘图状态,设置的都是ctx的状态,而ctx_copy的状态不变。
3,drawLine_2中的第4步,画第1根线的时候,使用的都是ctx中保存的状态,所以第1根线是红色,且线宽为10.
4,drawLine_2中的第5步,还原ctx,意思是将ctx还原成跟ctx_copy一样的状态,而ctx_copy中没有保存任何状态。所以。。。
以上4步根据这篇博客进行整理:http://www.cnblogs.com/wendingding/p/3782489.html
效果图:
图1 图2