2013-07-10 51 views
0

我收到以下錯誤,當我打電話的drawRect在我的自定義UIView子類:核芯顯卡錯誤

CGContextFillRects: invalid context 0x0 

在我UIView子類「EVGameView」被實現爲我的drawRect方法如下:

- (void)drawRect:(CGRect)rect 
{ 
    CGRect rectangle = CGRectMake(0, 100, 320, 100); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0); 
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); 
    CGContextFillRect(context, rectangle); 
} 

和我實例化我EVGameView類在我的viewController 'viewDidLoadMethod' 有:

- (void)viewDidLoad 
{ 
    srand(time(0)); 

    [super viewDidLoad]; 

    gameBoard = [[EVBoard alloc] init]; 
    [gameBoard initBoard:10 : 10 : mainBoard]; 

    gameView = [[EVGameView alloc] init];   // EVGameView instance 

      . 
      . 
      . 

} 

一個I撥打以下方法drawRect方法:

- (void)drawStartPosition 
{ 
    CGRect rect; 
    rect.origin = startPos; 
    rect.size.width = 10; 
    rect.size.height = 10; 
    [gameView drawRect: rect]; 
} 

似乎沒有上下文已經設置爲UIGraphicsGetCurrentContext()返回「零」。我在youTube上看到了一些例子,其中人們擁有相同的drawRect方法,並且工作正常。我在.xib文件中設置了一個單獨的視圖並將其鏈接到我的gameView實例,但仍然沒有運氣。 任何幫助,這是非常感謝!

Thanks-

回答

0

你不說,你叫drawStartPosition,但是這就是問題所在。基本上,您不應該自己致電drawRect:,而應該致電setNeedsDisplay並允許系統在實際要求您的視圖將自己吸收到提供的上下文之前完成所有適當的設置。

+0

O.K.謝謝,它的作品!我從視圖控制器中的另一個方法調用drawStartPosition。如果我需要傳遞一個CGRect,setNeedsDisplayInRect會工作嗎? – jdeckman

+0

'setNeedsDisplayInRect'將只顯示傳遞給屏幕的矩形。 – Wain

+0

不好意思再次發生,但是當我最初調用'setNeedsDisplay''drawRect'時,每次都會調用,因爲我在這裏設置了一個斷點。現在,當我調用前drawRect不再被調用。我做的唯一重大更改是在我的UIView子類接口中添加一個指向包含CGRect的對象的指針。有沒有聽說過這樣的事情?非常感謝您的幫助! – jdeckman