为什么会出现无效上下文错误?

7
这是我用来绘制的代码:
- (void) drawSomething
{

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
    CGContextSetLineWidth(context, 6.0);

    CGContextMoveToPoint(context, 100.0f, 100.0f);
    CGContextAddLineToPoint(context, 200.0f, 200.0f);
    CGContextStrokePath(context);

    NSLog(@"draw");

}

但是我遇到了这样的错误:
[Session started at 2010-04-03 17:51:07 +0800.]
Sat Apr  3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextSetRGBStrokeColor: invalid context
Sat Apr  3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextSetLineWidth: invalid context
Sat Apr  3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextMoveToPoint: invalid context
Sat Apr  3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextAddLineToPoint: invalid context
Sat Apr  3 17:51:09 MacBook.local MyApp[12869] <Error>: CGContextDrawPath: invalid context

为什么会提示我说上下文无效?

你从哪里调用drawSomething函数?那么当前的上下文应该是什么? - Kevin Reid
它从我的init方法调用。当前上下文不是当前视图吗? - Tattat
2个回答

12

就像文档所说:

默认情况下,当前的图形上下文为 nil。在调用其 drawRect: 方法之前,视图对象会将有效的上下文推送到堆栈中,使其成为当前上下文。

因此,您需要将此代码放入 drawRect 方法中。


4
iPhone OS是这样构建的:图形上下文(通过UIGraphicsGetCurrentContext()方法访问)只在需要时创建。当你想要绘制某些东西时才需要它,所以你需要在你的类中重写drawRect:方法。即使你可以直接调用drawRect:方法,iPhone SDK文档也建议你不要这样做。因此,不要仅仅将你的方法名从drawSomething:更改为drawRect:并直接调用它,虽然这样也能工作,但我建议你像@Brad Larson告诉你的那样使用setNeedsDisplay方法。 - Thomas Joulin
谢谢你们,你们非常有帮助。 - Tattat

8

我的回答这个类似的问题

如果要绘制到屏幕上,您需要将绘图代码放置在UIView的-drawRect:方法(或CALayer的–drawInContext:)中。要更新其内容,您需要在UIView或CALayer上调用-setNeedsDisplay 。在任何其他时间尝试绘制都会导致您看到的“无效上下文”错误。

另请参见这个问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接