2012-02-15 91 views
0

我在我的loadView方法中寫了下面的代碼。石英,矩形不顯示

//draw grid lines 
CGContextRef context = UIGraphicsGetCurrentContext(); 
CGFloat color[4] = {.5,0.5,1.0,1.0}; 
CGContextSetLineWidth(context, 2.0); 
CGContextSetStrokeColor(context, color); 
CGRect rect = CGRectMake(100.0, 200.0, 50.0, 50.0); 
CGContextAddRect(context, rect); 
CGContextDrawPath(context, kCGPathFillStroke); 

在我的應用程序中,我添加了一些UIButtons和UILabels到UIView。我想圍繞UILabels繪製一個矩形。

我NSLogged代碼的任何一方,並獲得兩個日誌之間的以下運行時輸出錯誤。

<Error>: CGContextSetStrokeColor: invalid context 0x0 

<Error>: CGContextAddRect: invalid context 0x0 

<Error>: CGContextDrawPath: invalid context 0x0 

我如何確保我得到一個有效的範圍內?我假設調用UIGraphicsGetCurrentContext();就足夠了。

回答

1

除非您正在繪製,否則沒有當前的圖形上下文。

將會有一個背景下,如果:

  • 你是在一個的drawRect方法
  • 您已經創建使用UIGraphicsContextBeginImageContextWithOptions()或類似的地方離屏背景。在這種情況下,您通常會將繪圖提取到UIImage對象中以備後用。
3

石英(CoreGraphics)代碼應該在drawRect:方法UIView中完成。

+0

好吧,我把代碼放在我的ViewController中的一個drawRect:(CGRect)方法中,它是UIView的一個子類。 drawRect中的代碼由這兩行調用CGRect rect = CGRectMake(100.0,200.0,50.0,50.0);它已經刪除了錯誤,但仍然沒有圖形的標誌。 [self.view drawRect:rect];在loadView方法中。 – 2012-02-15 18:08:06

+1

你不會調用'drawRect:',iOS會在適當的時候爲你做。你也確定你的ViewController是UIView的子類,而不是UIViewController? – gcamp 2012-02-15 18:51:45