【问题标题】:‘invalid context 0x0’ error when using CGContext* functions使用 CGContext* 函数时出现“无效上下文 0x0”错误
【发布时间】:2011-10-28 17:24:49
【问题描述】:
/*  Adding the Path */
UserGraphBuff = UIGraphicsGetCurrentContext();

CGContextSetRGBStrokeColor(UserGraphBuff,5,10,0,1);
CGContextSetLineWidth(UserGraphBuff, 2 );

CGContextBeginPath(UserGraphBuff);  

//line to last user point
CGContextAddLineToPoint(UserGraphBuff, (*xVal)[sizeof xVal / sizeof *xVal - 1], (*yNewVal)[sizeof yNewVal / sizeof *yNewVal - 1]);
//line to rest of user points in reverse order
for (int i = sizeof xVal / sizeof *xVal - 1; i > -1; i--){
    CGContextAddLineToPoint(UserGraphBuff, (*xVal)[i], (*yNewVal)[i]);
}

//EOFill
CGContextEOFillPath(UserGraphBuff);

以上是我正在尝试解决的代码。它应该按照 CGContext 所说的去做,但我没有画出任何东西。 我不断收到此错误:

Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextSetRGBStrokeColor: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextSetLineWidth: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextBeginPath: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextAddLineToPoint: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextDrawPath: invalid context 0x0

我在头文件中引用了 CGContextRef。

我认为我对 CGContext 的理解不够好,也不知道 CGContextRef 应该是什么。

【问题讨论】:

  • 这段代码在哪里?在UIView 子类的drawRect 中?
  • 那是什么鬼?它有什么作用?是-drawRect:调用的吗?

标签: cocoa-touch quartz-2d cgcontext


【解决方案1】:

要使您的代码正常工作,它需要在您的 UIView 子类的 drawRect 方法中执行(并且您不要直接调用 drawRect - 当操作系统需要 UIView 时调用它渲染自己)。您可能正试图从触摸事件或viewDidLoad 或类似的东西运行此代码。

【讨论】:

  • 它以自己的方式处理几件事。它不是单独调用的。我从一个检查事件中运行它。我希望用户数据与实际绘图交叉引用(它实际上是一个追踪游戏)。在这一点上,我只是想为绘制的人做好准备。
  • 重申一下:除非在 UIView 子类的 drawRect 方法中运行,否则您的代码将无法工作(意味着它会抛出您看到的错误)。
  • 并解释一下:UIView 在调用您的drawRect: 之前设置当前上下文。这是一个特点:你在需要绘图的时候绘图,系统会为你跟踪。不要与之抗争;将您的绘图代码移动到应有的位置,并使用系统。当视图需要重新绘制的某些更改时,将视图设置为需要显示。
  • @JohnRiselvato:不,他没有错。您正在查看比 UIKit 更低级别的 Quartz 文档。当 UIKit 告诉你时,你使用 Quartz 来绘制。涵盖drawRect:、需要显示等的文档是View Programming Guide for iOS。
  • @JohnRiselvato 抱歉,MusiGenesis 完全正确。这是正确的答案。
猜你喜欢
  • 2013-10-30
  • 2014-09-25
  • 1970-01-01
  • 2013-09-30
  • 2015-12-14
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
相关资源
最近更新 更多