Search code examples
iphoneiosquartz-graphics

Simple graph draw task for iPhone


I need to draw a simple graph, but I have no experience with custom draw iPhone graphics yet, so I hope, somebody can help me.

Task is simple: I need to draw graph background from .png file from resource, and draw points, also from bundled .png-files on some positions on background.

For drawing, I created descendant from UIView, and use following lines of code:

CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, 250, 500);
CGContextDrawImage(context, rect, [[UIImage imageNamed:@"graph.png"] CGImage]);

But its not working.

The first problem, I can't solve - UIGraphicsGetCurrentContext returns nil.

Can you help me?


Solution

  • I solved my problems with this code.

    - (void) drawGrid{
        UIImage *sourceImage = [UIImage imageNamed:@"sungraph.png"];
    
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(sourceImage.size.width, sourceImage.size.height), NO, 0);
    
        CGRect rectangle = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);
        self.frame = rectangle;
    
        [sourceImage drawInRect:rectangle];
    }
    
    - (void) finalizeImage{
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        imgView = [[UIImageView alloc] initWithImage:newImage];
        imgView.frame = CGRectMake(0, 0, newImage.size.width, newImage.size.height);
        [self addSubview:imgView];    
    }
    

    From initWithFrame of my class I call first function. After, I add some data to graph (draw lines, etc) And call finalizeImage at the end.