2012-02-05 70 views
1

我正在研究斯坦福大学CS193p课程,并试图绘制图形。绘制轴的工作原理,但我无法绘制图形本身。我收到消息在drawRect()方法中绘制CoreGraphics行的麻烦

CGContextAddLineToPoint: no current point. 

当我尝试绘制。这是代码。

- (void)drawRect:(CGRect)rect 
{ 
NSLog(@"Drawing Graph View"); 
CGPoint origin = CGPointMake(20, 350); 
CGRect rect2 = CGRectMake(origin.x, origin.y, 250, -250); 
[AxesDrawer drawAxesInRect:rect2 originAtPoint:origin scale:[self scale]]; 

CGContextRef context = UIGraphicsGetCurrentContext(); 



UIGraphicsPushContext(context); 

CGContextSetLineWidth(context, 2); 
[[UIColor redColor] setStroke]; 


CGContextMoveToPoint(context, origin.x, origin.y); 
for (CGFloat i=0; i<250; i++) { 

    CGFloat yChange = [self.dataSource deltaY:self]; 

    CGContextAddLineToPoint(context, origin.x+i, origin.y-yChange); 

    CGContextStrokePath(context); 

} 

UIGraphicsPopContext(); 

} 

回答

5

你必须把CGContextStrokePath(context);for循环外。否则,它将在循环的每次运行中创建一个新路径,并且失败。

+0

谢谢你的工作完美。 – MaxGabriel 2012-02-05 16:25:41

+0

多数民众赞成在我工作.. – 2013-11-27 10:32:36

2

你不是有问题:

CGRectMake(origin.x, origin.y, 250, -250) 

您指定一个负的高度!

+0

iOS中的坐标系统从左上角开始。因此,正值x值正确,正值y值下降。因此,为了使线条上升,我使用了一个负的y值作为CGRectMake的高度参数 – MaxGabriel 2012-02-05 21:03:05

+1

如果您正在绘制线条,则为true,但此过程(CGRectMake)定义了一个矩形。 – aleene 2012-02-06 16:21:17

+1

谢谢,这实际上证明是一个重要的错误修复。 – MaxGabriel 2012-02-12 19:37:53