UIImage来自文件问题

时间:2011-04-27 22:59:09

标签: iphone xcode ios uiimage

我正在尝试加载已保存的图像,但是当我检查UIImage时它会返回为零。这是代码:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"/var/mobile/Applications/B74FDA2B-5B8C-40AC-863C-4030AA85534B/Documents/70.jpg" ofType:nil]];

然后检查img以查看它是否为零。列出目录显示文件,我做错了什么?

4 个答案:

答案 0 :(得分:18)

您需要指向应用程序中的Documents目录,然后像这样:

- (NSString *)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

用法:

UIImage *img = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/70.jpg",[self applicationDocumentsDirectory]]];

答案 1 :(得分:8)

首先,您使用的是pathForResource错误,正确的方法是:

[[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"]

捆绑的整个想法是抽象资源路径,例如它始终有效,无论您的应用程序驻留在系统中的哪个位置。但是,如果您只想加载该图像,我建议您使用imageNamed:因为它会自动为您处理iPhone上的视网膜分辨率(高分辨率)显示检测,并“自动”加载相应的资源:

UIImage *img = [UIImage imageNamed:@"70.jpg"];

要轻松支持常规和视网膜分辨率,您需要在应用程序包中使用两个资源,70.jpg和70@2x.jpg,其中@ 2x资源的倍数和高度都是。

答案 2 :(得分:5)

尝试使用以下内容加载UIImage:

[UIImage imageNamed:@"something.png"]

它在应用程序的主包中查找具有指定名称的图像。也很好:它会自动选择Retina(xyz@2x.png)或非Retina(xyz.png)版本。

答案 3 :(得分:3)

您的路径根本无法工作,因为您的应用位于沙盒中,并且您正在尝试使用完整路径。

您应该使用以下内容:

  

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"]];

或者你可以使用,但比上面的要慢:

  

UIImage *img = [UIImage imageNamed:@"70.jpg"];