• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何使用 NSBundle 从指定的 PATH 或文档目录中获取图像

[复制链接]
菜鸟教程小白 发表于 2022-12-13 03:59:11 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我做了很多研究来找出以下代码的工作方式之间的区别。 当我试图从 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap