推送/弹出图形上下文

时间:2012-06-03 16:52:14

标签: ios5

我一直在浏览Standford University IOS lessons而且我一直在理解UIGraphicsPushContext和UIGraphicsPopContext的作用(第4课)。从注释中可以看出,这些方法可用于避免影响其他实用方法的当前图形状态。以下是注释中提供的示例:

- (void)drawGreenCircle:(CGContextRef)ctxt {

    UIGraphicsPushContext(ctxt);

    [[UIColor greenColor] setFill];

    // draw my circle 
    UIGraphicsPopContext();
}

- (void)drawRect:(CGRect)aRect {

    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor redColor] setFill];

    // do some stuff
    [self drawGreenCircle:context];

    // do more stuff and expect fill color to be red
}

但是,当我尝试测试时,我似乎没有得到这个结果。下面是我做的一个简单的测试用例,它获取drawRect中的当前上下文,设置颜色,调用一个实用程序方法,将颜色设置为绿色,返回drawRect并绘制一条线。我希望根据Standford网站上的注释,由于我在drawGreenCircle中推送/弹出上下文,因此该线条将为红色。 (我意识到我实际上并没有在drawGreenCircle中绘制任何圆圈)但是我在drawRect中得到了一条绿线。似乎我的drawGreenCircle方法确实改变了颜色并且没有将它恢复为红色。我想知道我对这个概念缺少什么。

- (void)drawGreenCircle:(CGContextRef)ctxt {
    //Doesn't actually draw circle --Just testing if the color reverts
    //to red in drawRect after this returns
    UIGraphicsPushContext(ctxt);
    [[UIColor greenColor] setStroke];   
    UIGraphicsPopContext();
}


- (void)drawRect:(CGRect)aRect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor redColor] setStroke];
    // do some stuff
    [self drawGreenCircle:context];
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 100, 100);
    CGContextAddLineToPoint(context, 500, 100);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}

1 个答案:

答案 0 :(得分:2)

您需要CGContextSaveGStateCGContextRestoreGState。以下代码有效:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor greenColor] setFill];
    [[UIColor blackColor] setStroke];
    [self drawBlueCircle:context];
    CGContextMoveToPoint(context, 55, 5);
    CGContextAddLineToPoint(context, 105, 100);
    CGContextAddLineToPoint(context, 5, 100);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}

- (void)drawBlueCircle:(CGContextRef)context {
    CGContextSaveGState(context);
    [[UIColor blueColor] setFill];
    CGContextAddEllipseInRect(context, CGRectMake(0, 0, 100, 100));
    CGContextDrawPath(context, kCGPathFillStroke);
    CGContextRestoreGState(context);
}

Source