James Douglas
James Douglas

Reputation: 736

Drawing line graph using Quartz?

I am trying to make a simple graph for the ipad. I need to plot sin(x), cos(x) and tan(x) functions using QUARTZ. I know how to make the grid and the lines, but have no idea how to start with this. Any help is appreciated.

Please note I am not interested in core plot and other frameworks so please don't offer this as an answer.

Upvotes: 1

Views: 614

Answers (1)

user529758
user529758

Reputation:

Simple: you decide what resolution/precision you want, then you split the domain of the functions into intervals according to that, you calculate the values of the function in each interval and you connect those with a straight line:

// Within a subclass of UIView
- (void)drawFunction:(double (*)(double))fn from:(double)x1 to:(double)x2
{
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGFloat comps[] = { 1.0, 0.0, 0.0, 1.0 };
    CGContextSetStrokeColor(ctx, comps);
    CGContextSetLineWidth(ctx, 2.0);

    const double dx = 0.01; // precision
    double scale_x = self.bounds.size.width / (x2 - x1);
    double off_x = 0.0;
    double scale_y = scale_x;
    double off_y = self.bounds.size.height / 2;

    CGContextMoveToPoint(ctx, x1 * scale_x - off_x, off_y - fn(x1) * scale_y);

    for (double x = x1 + dx; x <= x2; x += dx) {
        double y = fn(x);
        CGFloat xp = x * scale_x - off_x;
        CGFloat yp = off_y - y * scale_y;
        CGContextAddLineToPoint(ctx, xp, yp);
    }

    CGContextStrokePath(ctx);
}

Call this from - drawRect::

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    [self drawFunction:sin from:0.0 to: 2 * M_PI];
}

Upvotes: 2

Related Questions