为什么会出现无效上下文错误?
这是我用来绘制的代码:
- (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
为什么它提示我说上下文无效?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像 该文档说:
所以你需要把这段代码放在drawRect方法中
Like the documentation says :
So you need to put this code in the drawRect method
从我的回答到这个类似的问题:
如果要绘制到屏幕上,您'您需要在 UIView 的
-drawRect:
方法(或 CALayer 的–drawInContext:
)中找到绘图代码。要更新其内容,您需要在 UIView 或 CALayer 上调用-setNeedsDisplay
。在任何其他时间尝试绘图都会导致您看到“无效上下文”错误。另请参阅此问题。
From my answer to 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-setNeedsDisplay
on the UIView or CALayer. Attempting drawing at any other time will cause the "invalid context" error you're seeing.See also this question.