OGeek|极客世界-中国程序员成长平台

标题: ios - 如何使用 NSBundle 从指定的 PATH 或文档目录中获取图像 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:59
标题: ios - 如何使用 NSBundle 从指定的 PATH 或文档目录中获取图像

我做了很多研究来找出以下代码的工作方式之间的区别。 当我试图从 PATH 使用 NSBundle 指定的文档目录中获取图像并将其显示在 ImageView 中时。

类型 1: 此代码工作正常,能够检索图像并显示:

NSString *inputPath= @"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png";
NSString *jjj=[inputPath pathExtension];
NSString *hhhhh=[[inputPath lastPathComponent]stringByDeletingPathExtension];
NSString *bivivik=[inputPath stringByDeletingLastPathComponent];
NSString *imagePATH=[NSBundle pathForResource:hhhhh ofType:jjj inDirectory:bivivik];
theImage=[UIImage imageWithContentsOfFile:imagePATH];
mImageDisplayView.image=theImage;

类型 2: 但是如果我尝试如下代码。不获取图像并显示空值

NSString* imagepath = [[NSBundle bundleWithPath"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png"]bundlePath];
theImage=[UIImage imageWithContentsOfFile:imagepath];
mImageDisplayView.image=theImage;

我的 TYPE 2 代码有什么问题。有没有其他方法可以像我在 TYPE 2 方法中尝试的那样获取图像。请帮助我



Best Answer-推荐答案


尽管上面的代码在一个实例中有效,但两个代码片段都是错误的,因为它们无法读取设备上的文件。原因是,您正在使用模拟器能够找到的 MAC 中的绝对路径,但在设备上不存在。

使用 [NSBundle mainBundle] 从应用程序包中读取文件,

[[NSBundle mainBundle] pathForResource"imageName" ofType"png"];

要从应用程序的文档目录中读取文件,请使用此代码段,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent"Myfile.png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];

编辑

如果您有一个包含图像文件的单独包,则要从该包中读取,请使用此代码段。假设这个包在文档目录中,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *bundlePath = [[paths objectAtIndex:0] stringByAppendingPathComponent"MyBundle.bundle"];
NSBundle *myBundle = [NSBundle bundleWithPath:bundlePath];
NSString* imagePath = [myBundle pathForResource"MyImage" ofType"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];

希望有帮助!

关于ios - 如何使用 NSBundle 从指定的 PATH 或文档目录中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18573163/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4