ios-day14-02(Quartz 2D之图形上下文栈)

源码下载地址: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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值