iOS使用Quartz 2D绘制形状 - 无效的上下文错误

时间:2011-10-15 13:57:07

标签: ios core-graphics

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

- (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”的值为:

con = (CGContext)0x0

1 个答案:

答案 0 :(得分:2)

您的代码存在的问题是,您不应该尝试绘制。

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