0

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?

Andrey
  • 2,659
  • 4
  • 29
  • 54

2 Answers2

1

You probably forgot to add your View in your xib/storyboard.

In your story board open the utilities menu and add a View to the screen you are trying to draw into. Then change the class of the View to your class that extends View.

You can follow this tutorial in the section "Using the 5 Star Rating View" to add your View into storyboard.

For more information you can:

  • Follow this answer on stackoverflow
  • Check if you made all steps necessary for your costum View in the tutorial or following this blog (this blog doesn't have the storyboard part)
Community
  • 1
  • 1
Tiago Almeida
  • 14,081
  • 3
  • 67
  • 82
0

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.

Andrey
  • 2,659
  • 4
  • 29
  • 54
  • You are adding a subView that is the same that I said if you use the interface builder. Don't know if that was the only problem ;) – Tiago Almeida Sep 29 '12 at 19:48