2011-10-15 37 views
0

这可能是一件简单的事情。我试图在我的ViewDidLoad中绘制我的第一个形状。然而,我的上下文总是空,我得到“con = 0x0”。我不确定我是否正确使用它。我在下面粘贴了我的代码。使用Quartz 2D的iOS绘制形状 - 无效的上下文错误

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // obtain the current graphics context 

    CGContextRef con = UIGraphicsGetCurrentContext(); 

    // draw a black (by default) vertical line, the shaft of the arrow 

    CGContextMoveToPoint(con, 100, 100); 
    CGContextAddLineToPoint(con, 100, 19); 
    CGContextSetLineWidth(con, 20); 
    CGContextStrokePath(con); 

    // draw a red triangle, the point of the arrow 

    CGContextSetFillColorWithColor(con, [[UIColor redColor] CGColor]); 
    CGContextMoveToPoint(con, 80, 25); 
    CGContextAddLineToPoint(con, 100, 0); 
    CGContextAddLineToPoint(con, 120, 25); 
    CGContextFillPath(con); 

    // snip a triangle out of the shaft by drawing in Clear blend mode 

    CGContextMoveToPoint(con, 90, 101); 
    CGContextAddLineToPoint(con, 100, 90); 
    CGContextAddLineToPoint(con, 110, 101); 
    CGContextSetBlendMode(con, kCGBlendModeClear); 
    CGContextFillPath(con); 

} 

当调试,“骗子”的值是:

con = (CGContext)0x0 

回答

2

与您的代码的问题是,你想,当你不应该画。

您可以将您的绘图代码视图中的drawRect:方法,因为操作系统准备的上下文,可以在其中调用drawRect:之前绘制,也可以创建自己的上下文并吸引到它,将其导出为图像并使用UIImageView显示它。

+0

非常感谢您的反馈! –