无效的上下文0x0

时间:2012-08-13 19:04:06

标签: objective-c cgcontext

我在视图中有这个-drawRect方法:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
for (int i=0; i<[points count]; i++) {
    GraphPoint* point = [points objectAtIndex:i];
    [point.color setFill];
    [[UIColor blackColor] setStroke];
    CGContextBeginPath(context);
    CGContextAddArc(context, point.x+point.size/2, point.y+point.size/2, point.size, 0, 2*M_PI, 0);
    CGContextFillPath(context);
    CGContextStrokePath(context);
    UIGraphicsPopContext();
}

[points count]等于1时,一切都会令人惊讶,但是,当它增加时,会抛出此错误:

Error>: CGContextSetStrokeColorWithColor: invalid context 0x0.

我认为循环有问题 - 它将上下文的颜色设置两次甚至更多次。不知道如何避免它。每个点必须有自己的颜色,我不能在循环之前设置上下文的填充颜色。

请帮忙!也许有人遇到过这个问题?

2 个答案:

答案 0 :(得分:3)

你误解了UIGraphicsPopContext的功能。我假设您正在尝试清除在上下文中设置的当前路径。您需要CGContextSaveGStateCGContextRestoreGState

试试这个:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
for (int i=0; i<[points count]; i++) {
    CGContextSaveGState(context);
    {
        GraphPoint* point = [points objectAtIndex:i];
        [point.color setFill];
        [[UIColor blackColor] setStroke];
        CGContextBeginPath(context);
        CGContextAddArc(context, point.x+point.size/2, point.y+point.size/2, point.size, 0, 2*M_PI, 0);
        CGContextFillPath(context);
        CGContextStrokePath(context);
    }
    CGContextRestoreGState(context);
}

N.B。我通常在使用基于堆栈的操作(推送和弹出)时创建一个新的范围(使用额外的{}),这样就可以很容易地检查它们是否平衡。当然,这是可选的。

答案 1 :(得分:1)

你在每个循环中弹出上下文,但是你没有推动它。所以你在上下文堆栈上的上下文用完了。

删除UIGraphicsPopContext调用并查看它是否修复了它。

相关问题