Search code examples
iphoneobjective-cgraphquartz-graphics

Smooth lines drawing graph with Quartz


I'm doing a graph with Quartz, following this tutorial.

This is my hard-coded class:

#import "GraphView.h"

#define kGraphHeight 110
#define kDefaultGraphWidth 900
#define kOffsetX 0
#define kStepX 50
#define kStepY 50
#define kOffsetY 10
#define kGraphBottom 110
#define kGraphTop 0
#define kBarTop 10
#define kBarWidth 40
#define kCircleRadius 3

@implementation GraphView

float data[] = {0.7, 0.4, 0.9, 1.0, 0.2, 0.85, 0.11, 0.75, 0.53, 0.44, 0.88, 0.77, 0.99, 0.55};

- (void)drawLineGraphWithContext:(CGContextRef)ctx
{
    CGContextSetLineWidth(ctx, 0.2);
    CGContextSetStrokeColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);

    int maxGraphHeight = kGraphHeight - kOffsetY;

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, kOffsetX, kGraphHeight - maxGraphHeight * data[0]);
    for (int i = 1; i < sizeof(data); i++)
    {
        CGContextAddLineToPoint(ctx, kOffsetX + i * kStepX, kGraphHeight - maxGraphHeight * data[i]);
    }
    CGContextDrawPath(ctx, kCGPathStroke);
    CGContextSetFillColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(context, true);
    for (int i = 0; i < sizeof(data); i++)
    {
        [self drawLineGraphWithContext:context];
    }
}

@end

And this is the result:

enter image description here

As you can see, the lines can't be any less smooth. They don't look good at all. Tried with antialiasing but nothing changed, how can i improve the lines quality?

Thanks!


Solution

  • Your line width should be 2.0, not 0.2. It will struggle to draw you a decent line that small.

    Also it appears that you are drawing the graph n times, where n is your number of data points - you have a for loop in your drawRect and in your drawInContext method.

    You shouldn't need to set any antialiasing, the default should see you right.