1

I'm working on the Stanford CS193p course and am trying to draw a graph. Drawing the axes works, but I can't draw the graph itself. I'm getting the message

CGContextAddLineToPoint: no current point.

when I try to draw. Here's the code.

- (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();

}
MaxGabriel
  • 7,617
  • 4
  • 35
  • 82

2 Answers2

5

You have to place CGContextStrokePath(context); outside the for loop. Otherwise it will create a fresh path on every run through the loop and that fails.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
2

Do you not have a problem with:

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

You specify a negative height!

aleene
  • 334
  • 2
  • 8
  • The coordinate system in iOS starts from the top left corner. Thus positive x values go right, positive y-values go down. Thus to make a line going up I'm using a negative y value for the height argument of CGRectMake – MaxGabriel Feb 05 '12 at 21:03
  • 1
    True if you are drawing lines, but this procedure (CGRectMake) defines a rectangle. – aleene Feb 06 '12 at 16:21
  • 1
    Thanks, this actually turned out to be an important bug fix. – MaxGabriel Feb 12 '12 at 19:37