【问题标题】:Why there is an invalid context error?为什么会出现无效的上下文错误?
【发布时间】:2010-04-03 19:58:39
【问题描述】:

这是我用来绘制的代码:

- (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?那么当前的上下文应该是什么?
  • 它从我的 init 方法中调用。当前上下文不是当前视图?

标签: iphone objective-c xcode quartz-graphics


【解决方案1】:

就像the documentation 说的:

当前图形上下文默认为 nil。在调用它的 drawRect: 方法之前,视图对象将一个有效的上下文压入堆栈,使其成为当前的。

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

【讨论】:

  • iPhone OS 的构建使得图形上下文(我们可以通过 UIGraphicsGetCurrentContext() 访问)仅在需要时创建。当您想要绘制某些东西时,这是需要的,因此在您将在您的类中覆盖的 drawRect: 方法中。即使您可以直接调用 drawRect:,iPhone SDK 文档也建议您不要这样做。因此,不要只是将您的方法 drawSomething: 重命名为 drawRect: 并调用它,这会起作用,我建议您这样做,但像 @Brad Larson 告诉您的那样调用 setNeedsDisplay ;)
  • 伙计们,你们很有帮助。
【解决方案2】:

my answerthis similar question

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

另见this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 2020-03-26
    • 1970-01-01
    • 2019-01-02
    • 2019-08-26
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多