kiran
kiran

Reputation: 4409

Drawing graph line using Core Graphics

I am trying draw an random graph which display on imageview, I try this code

-(void)createGraph{
        UIGraphicsBeginImageContext(self.drawImage.frame.size);
        [drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];    
        CGContextRef context    = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetLineWidth(context, 2.0);
        int i = 0;
        while (i<=20) {
            int r = rand() % 100;

            CGContextMoveToPoint(context, 20, 320);
            CGContextAddLineToPoint(context, linePoint.x+20+i*r, linePoint.y+320-i*r);         
            CGContextStrokePath(context);   
            i++;

            NSLog(@"random value %d",r);
        }
        drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    }

But its drawing a diagonal on single line. has show in below image

I am expecting to draw a graph line! using coregraphics enter image description here

Upvotes: 0

Views: 1901

Answers (2)

TheTiger
TheTiger

Reputation: 13354

- (void)viewDidLoad
{
    //X_Line, Y_Line, x and y are integer variables
    X_Line = 20;
    Y_Line = 320;
    for(int i=0; i<10; i++)
    {
        x = x + arc4random() % 100;
        y = x + arc4random() % 100;
        [self createGraph];
    }
}

-(void)createGraph
{  
    UIGraphicsBeginImageContext(imgView.frame.size);
    [imgView.image drawInRect:CGRectMake(0, 0, imgView.frame.size.width, imgView.frame.size.height)];    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetLineWidth(context, 2.0);
    CGContextMoveToPoint(context, X_Line, Y_Line);
    CGContextAddLineToPoint(context, x , y);         
    CGContextStrokePath(context);   
    imgView.image = UIGraphicsGetImageFromCurrentImageContext();

    X_Line = x;
    Y_Line = y;
}

Upvotes: 1

John Smith
John Smith

Reputation: 2022

First of all, you cannot put CGContextAddLineToPoint into the loop. Remove (just) the loop, and make another loop in e.g. viewDidLoad, at each iteration, call -(void)createGraph giving the last point and the next one. Now the last point you will assign to CGContextMoveToPoint, and the next point you will give to CGContextAddLineToPoint. By the way, add CGContextBeginPath(context); right after CGContextSetLineWidth(context, 2.0);

Upvotes: 1

Related Questions