为什么我在以下Core Graphics代码中收到“无效上下文”错误?

时间:2011-08-10 05:49:21

标签: iphone objective-c ios core-graphics

我有以下图纸代码:

    static int i=10;
    int x;
    int y;
    int x2;
    int y2;
    // Drawing code.
    CGContextRef c = UIGraphicsGetCurrentContext();    
    CGFloat colour[4] = {1.0f,0.0f,0.0f,1.0f};
    CGContextSetStrokeColor(c, colour);
    CGContextSetLineWidth(c, 1.0);
    CGContextBeginPath(c);
    NSLog(@"fired...");
    int xline[340] = {30,80,80,20};     
    int yline[340] = {40,40,20,20};
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, x, y);
    CGContextAddLineToPoint(c,x2,y2);
    //CGContextStrokePath(c);    
    for (int j = 0; j <= 3; j++) {
        x2 = xline[j];
        y2 = yline[j];
        CGContextAddLineToPoint(c, x2, y2);
        x = x2;
        y = y2;
    }    
    CGContextStrokePath(c); 
    [self setNeedsDisplay];
    i++;

但是,当它运行时,我收到以下错误:

Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextBeginPath: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextMoveToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextAddLineToPoint: invalid context 0x0
Wed Aug 10 11:13:05 Mac-Minis-Mac-mini.local LineDraw[1880] <Error>: CGContextDrawPath: invalid context 0x0

什么可能导致这些错误,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:8)

除非您在drawRect:子类的UIView方法中使用此代码,或者已将图形上下文专门推送到堆栈上(例如,使用UIGraphicsBeginImageContext),UIGraphicsGetCurrentContext()将返回NULL

所有绘图功能都需要图形上下文。

答案 1 :(得分:1)

如果您想获得有关如何绘制矩形线等的信息,请查看this link,其中您将获得完整的信息。