2011-08-10 28 views
4

我有以下繪圖代碼:爲什麼我在下面的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 

什麼會引起這些錯誤,我怎麼能解決這個問題?

+1

我無法相信有人投這個問題,關閉... – Robin

回答

8

除非你有在UIView子類的drawRect:方法此代碼或已明確推圖形上下文壓入堆棧(例如,通過使用UIGraphicsBeginImageContext),UIGraphicsGetCurrentContext()將返回NULL

所有繪圖函數都需要圖形上下文。

+0

在我具體的例子,我開始與'UIGraphicsBeginImageContext'但是,如果它很重要,我在一個線程這樣做(並且可能還有其他線程試圖做類似的繪圖。)因此,它對前幾十個圖像正常工作,然後在下一個圖像上失敗。想法? – Olie

1

如果你想獲得關於如何繪製矩形線等的信息,然後檢查this link在哪裏你會得到完整的信息。

相關問題