Skip to content

Instantly share code, notes, and snippets.

@MaxGabriel
Created February 12, 2012 20:39
Show Gist options
  • Save MaxGabriel/1810765 to your computer and use it in GitHub Desktop.
Save MaxGabriel/1810765 to your computer and use it in GitHub Desktop.
drawRect Method for GraphView
//Draws a Cartesian Coordinate system and graphs an equation on it.
//Equation comes from GraphViewController (data source)
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint midPoint; //center in coordinate system
midPoint.x = self.bounds.origin.x + self.bounds.size.width/2;
midPoint.y = self.bounds.origin.y + self.bounds.size.height/2;
//Draw Axes
CGRect rect1 = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
[AxesDrawer drawAxesInRect:rect1 originAtPoint:midPoint scale:[self scale]];
UIGraphicsPushContext(context);
//Set Drawing Options
CGContextSetLineWidth(context, 2);
[[UIColor redColor] setStroke];
//Draw Graph
BOOL haveMovedToPoint = NO;
for (CGFloat pixel = 0; pixel < midPoint.x*2; pixel++) { //Iterate over each pixel left to right, iOS coordinat system
//Change frame of reference to Cartesian coordinate system
CGFloat xPixelsFromCartesianOrigin = pixel-midPoint.x; //Distance from center to edge of screen
xValue = xPixelsFromCartesianOrigin / [self scale]; //xValue in Units
CGFloat yChange = [self.dataSource deltaY:self]; //Delegate calculates y-Value in units given x-Value in units
CGFloat yPixelsFromCartesianOrigin = yChange * [self scale];
//If this is the first iteration through the loop, move to point to begin drawing.
if (haveMovedToPoint == NO)
{
CGContextMoveToPoint(context, 0, (self.bounds.size.height/2)-yPixelsFromCartesianOrigin);
haveMovedToPoint = YES;
}
CGContextAddLineToPoint(context, pixel, (self.bounds.size.height/2)-yPixelsFromCartesianOrigin);
}
CGContextStrokePath(context);
UIGraphicsPopContext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment