2010-08-21 35 views
1

我試圖劃一條線。在iPhone中畫一條線,例外

我寫了如下代碼。

UIColor *currentColor = [UIColor blackColor]; 

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextSetLineWidth(context, 2.0); 
CGContextSetStrokeColorWithColor(context, currentColor.CGColor); 
CGContextMoveToPoint(context, startingPoint.x, startingPoint.y); 
CGContextAddLineToPoint(context,endingPoint.x , endingPoint.y); 
CGContextStrokePath(context); 

但這顯示例外如下

Sat Aug 21 10:47:20 AAA-rrr-Mac-mini.local Test[2147] <Error>: CGContextSetLineWidth: invalid context 0x0 
Sat Aug 21 10:47:20 AAA-rrr-Mac-mini.local Test[2147] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0 
Sat Aug 21 10:47:20 AAA-rrr-Mac-mini.local Test[2147] <Error>: CGContextMoveToPoint: invalid context 0x0 
Sat Aug 21 10:47:20 AAA-rrr-Mac-mini.local Test[2147] <Error>: CGContextAddLineToPoint: invalid context 0x0 
Sat Aug 21 10:47:20 AAA-rrr-Mac-mini.local Test[2147] <Error>: CGContextDrawPath: invalid context 0x0 
+0

之前您實際上並沒有一個圖形上下文。你是在一個drawRect裏面做這個的:還是其他一些隨機的地方? – 2010-08-21 05:27:35

+0

即時通訊使用它在我自己的函數名爲drawLine:(CGPoint)來自:(CGPoint)要 – 2010-08-21 05:42:36

+0

應該包括任何框架或一些文件的繪圖? – 2010-08-21 05:43:35

回答

4

您還需要調用CGContextBeginPath(ctx);你打電話CGContextMoveToPoint

- (void) drawRect: (CGRect) rect 
{ 
    UIColor *currentColor = [UIColor blackColor]; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor); 
    CGContextBeginPath(context); // <---- this 
    CGContextMoveToPoint(context, self.bounds.origin.x, self.bounds.origin.y); 
    CGContextAddLineToPoint(context, self.bounds.origin.x + self.bounds.size.x, self.bounds.origin.y + self.bounds.size.y); 
    CGContextStrokePath(context); 
} 
+0

您還需要使用'CGContextClosePath' – 2014-05-18 14:13:22

2

你有沒有有效的圖形上下文。 UIGraphicsGetCurrentContext()顯然返回nil

你想在哪裏畫?

如果你想繪製到屏幕上,那麼你應該實現drawRect:方法UIView或它的一個子類,並讓iOS調用該方法(通過觸發刷新屏幕的一部分)。然後在執行drawRect:期間,您將擁有有效的圖形上下文。

如果要繪製到離屏像素圖,則必須使用UIGraphicsBeginImageContext或類似函數自己創建圖形上下文。

編輯:

所以繪製成的UIView,你需要創建一個的UIView子類並覆蓋的drawRect:

@interfaceMyView : UIView { 
} 

@end 


@implementation MyUIView 

- (void) drawRect: (CGRect) rect 
{ 
    UIColor *currentColor = [UIColor blackColor]; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextSetStrokeColorWithColor(context, currentColor.CGColor); 
    CGContextMoveToPoint(context, self.bounds.origin.x, self.bounds.origin.y); 
    CGContextAddLineToPoint(context, self.bounds.origin.x + self.bounds.size.x, self.bounds.origin.y + self.bounds.size.y); 
    CGContextStrokePath(context); 
} 

然後打開XIB文件(你可能在Interface Builder中已經有了=,在那裏添加一個UIView並選擇MyUIView作爲類(第一個字段在檢查器窗口的最後一個選項卡上)。

+0

你可以舉一個小例子。 – 2010-08-24 01:30:41

+0

我可以給你一個例子,如果你回答你想要畫的地方。 – Codo 2010-08-24 06:41:03

+0

我想在UIView中畫一條線 – 2010-08-25 03:03:56