繁体   English   中英

iPhone的简单图形绘制任务

[英]Simple graph draw task for iPhone

我需要绘制一个简单的图形,但是我还没有使用自定义绘制iPhone图形的经验,所以希望有人可以帮助我。

任务很简单:我需要从资源中的.png文件中绘制图形背景,并从背景中某些位置上的捆绑的.png文件中绘制点。

为了进行绘制,我从UIView创建了后代,并使用以下代码行:

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

但是它不起作用。

第一个问题,我无法解决-UIGraphicsGetCurrentContext返回nil。

你能帮助我吗?

您可能忘记了将视图添加到xib / storyboard中。

在故事板上,打开实用程序菜单,然后在试图绘制的屏幕上添加一个视图。 然后将View的类更改为扩展View的类。

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

有关更多信息,您可以:

  • 在stackoverflow上遵循此答案
  • 检查您是否已完成所有必要的步骤,以查看本教程中的内容或关注此博客 (此博客没有情节提要部分)

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

- (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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM