以下是我用来绘制的代码:
- (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
为什么它会促使我说上下文无效?
答案 0 :(得分:12)
默认情况下,当前图形上下文为零。在调用drawRect:方法之前,视图对象将有效的上下文推送到堆栈,使其成为当前的。
所以你需要把这段代码放在drawRect方法
中答案 1 :(得分:8)
从my answer到this similar question:
如果要将其绘制到屏幕上,则需要在UIView(或CALayer的-drawRect:
)的–drawInContext:
方法中找到您的绘图代码。要更新其内容,您需要在UIView或CALayer上调用-setNeedsDisplay
。在任何其他时间尝试绘图将导致您看到的“无效上下文”错误。