为什么存在无效的上下文错误?

Tat*_*tat 7 iphone xcode objective-c quartz-graphics

这是我用来绘制的代码:

- (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");

}
Run Code Online (Sandbox Code Playgroud)

但是我得到了这样的错误:

[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
Run Code Online (Sandbox Code Playgroud)

为什么它促使我说上下文无效?

Tho*_*lin 12

就像文档说的那样:

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

所以你需要把这段代码放在drawRect方法中

  • 构建iPhone OS,以便仅在需要时创建图形上下文(通过UIGraphicsGetCurrentContext()可访问).当你想绘制某些东西时需要这样,所以在你的类中将覆盖的drawRect:method中.即使您可以直接调用drawRect:,iPhone SDK文档建议您不要.因此,不要只是重命名你的方法drawSomething:to drawRect:并调用它,这将起作用,我建议你这样做,但调用setNeedsDisplay就像@Brad Larson告诉你的那样;) (4认同)

Bra*_*son 8

这个类似问题的回答:

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

另见这个问题.