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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2570846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:15:33  来源:igfitidea点击:

Why there is an invalid context error?

iphoneobjective-cxcodequartz-graphics

提问by Tattat

Here is the code I use to draw:

这是我用来绘制的代码:

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

}

But I got the error like this:

但我得到了这样的错误:

[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

Why it prompt me to say that the context is invalided?

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

回答by Thomas Joulin

Like the documentationsays :

就像文档说的:

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current.

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

So you need to put this code in the drawRect method

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

回答by Brad Larson

From my answerto this similar question:

这个类似问题的回答

If this is to be drawn to the screen, you'll need to locate your drawing code within the -drawRect:method of a UIView (or –drawInContext:of a CALayer). To update its contents, you'd need to call -setNeedsDisplayon the UIView or CALayer. Attempting drawing at any other time will cause the "invalid context" error you're seeing.

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

See also this question.

另请参阅此问题