2013-08-03 32 views
0

我有畫一條線。我使用下面code.My實際需要是畫出從點存在於一個NSMutableArray無效的上下文爲0x0

- (void)drawLineGraph:(NSMutableArray *)lineGraphPoints 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextSetLineWidth(context, 1.0f); 
    CGContextMoveToPoint(context, 10, 10); 
    CGContextAddLineToPoint(context, 100, 50); 
    CGContextStrokePath(context); 
} 

線I接收的上下文作爲nil.I收到以下錯誤

Aug 3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0 
Aug 3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextSetLineWidth: invalid context 0x0 
Aug 3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextMoveToPoint: invalid context 0x0 
Aug 3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextAddLineToPoint: invalid context 0x0 
Aug 3 10:46:04 ABC-Mac-mini.local Sample[2077] <Error>: CGContextDrawPath: invalid context 0x0 

陣列lineGraphPoints有即是點plotted.Can任何人幫我畫一條線圖?

+0

這個函數是從'drawRect:'內調用的嗎?如果不是,那麼'UIGraphicsGetCurrentContext()'將返回nil。 – 2013-08-03 05:42:01

+0

@ H2CO3:謝謝,它工作正常 –

回答

1

你所問的很容易通過枚舉CGPoint值來完成。還要確保覆蓋drawRect:方法並在其中添加繪圖代碼。有關如何使用可變數組中的CGPoint值在圖形上下文中構造一條線,請參見下面的示例。

- (void)drawRect:(CGRect)rect { 
    NSMutableArray *pointArray = [[NSMutableArray alloc] initWithObjects: 
    [NSValue valueWithCGPoint:CGPointMake(10, 10)], 
    [NSValue valueWithCGPoint:CGPointMake(10, 10)], 
    [NSValue valueWithCGPoint:CGPointMake(12, 16)], 
    [NSValue valueWithCGPoint:CGPointMake(20, 22)], 
    [NSValue valueWithCGPoint:CGPointMake(40, 100)], nil]; 

    // Drawing code 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextSetLineWidth(context, 1.0f); 

    for (NSValue *value in pointArray) { 
    CGPoint point = [value CGPointValue]; 

     if ([pointArray indexOfObject:value] == 0) { 
      CGContextMoveToPoint(context, point.x, point.y); 
     } else { 
      CGContextAddLineToPoint(context, point.x, point.y); 
     } 
    } 

    CGContextStrokePath(context); 
    [pointArray release]; 
} 

我實例化drawRect方法中的可變數組,但你可以在你的頭文件中聲明它的實例和實例無論你喜歡和你的點值添加到它。

+0

謝謝它的工作正常 –

相關問題