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?

4

2 回答 2

1

您可能忘记在您的 xib/storyboard 中添加您的视图。

在您的故事板中打开实用程序菜单并将视图添加到您尝试绘制的屏幕。然后将 View 的类更改为扩展 View 的类。

您可以按照“使用 5 星评级视图”部分中的本教程将您的视图添加到情节提要中。

如需更多信息,您可以:

  • 在stackoverflow上关注这个答案
  • 检查您是否在教程中或关注此博客(此博客没有情节提要部分)中完成了您的服装所需的所有步骤
于 2012-09-22T19:20:18.790 回答
0

我用这段代码解决了我的问题。

- (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];    
}

从我班级的initWithFrame我调用第一个函数。之后,我将一些数据添加到图形(画线等)并在最后调用finalizeImage

于 2012-09-28T22:53:03.887 回答