imageNamed和imageWithContentsOfFile-无法加载图片的问题
来源:互联网 发布:贵阳网络广播电视台 编辑:程序博客网 时间:2024/05/16 09:34
问题描述
图片资源放在Assets.xcassets中,分别用UIImage的类方法imageNamed和imageWithContentsOfFile获取图片对象,但发生奇怪的情况,前者获取到图片对象,后者结果为nil。代码如下:
1.通过UIImage的类方法imageNamed:可以获取到图片对象。
UIImage *imge = [UIImage imageNamed:@"test.jpg"];
2.但通过UIImage的类方法imageWithContentsOfFile:得到img为nil
//NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];NSString *path = [[NSBundle mainBundle] pathForResource:@"test.jpg" ofType:nil];UIImage *imge = [UIImage imageWithContentsOfFile:path];
问题分析
其实,UIImage创建对象有两种方法:
- imageNamed:创建的对象会缓存到系统内存中,不会立即释放到内存。好处是再次加载使用这种方式会减少读取操作,加快程序运行。缺点:加载过多图片会占用大量内存空间。
- 创建图片对象,首先在缓存中查找是否有该对象,有则直接取出对象,
- 没有则从bundle中查找图片资源,有则创建对象并返回。
- bundle中也没有图片资源,则返回nil。
- imageWithContentsOfFile:mageWithContentsOfFile创建的对象不会缓存到系统内存中。好处是不产生缓存。缺点:对于经常使用的小图片,会频繁读取。
imageNamed只需传文件名,imageWithContentsOfFile需要传入文件全路径,而文件全路径可以通过NSBundle得到。
注意:
如果在项目中的Assets.xcassets(蓝色文件夹)
- 不可以NSBundle获得资源路径,然后imageWithContentsOfFile加载
- 可以imageNamed加载
如果在项目中真实文件夹(蓝色文件夹,除Assets.xcassets):
- 可以NSBundle获得资源路径,然后imageWithContentsOfFile加载。注意要带文件夹路径,例如[[NSBundle mainBundle]pathForResource:@"test.jpg" ofType:nil inDirectory:@"image"]
- 不可以imageNamed加载
如果在项目中虚拟文件夹(黄色文件夹):
- 可以NSBundle获得资源路径,然后imageWithContentsOfFile加载
- 可以imageNamed加载
问题解决
只能imageNamed获取Assets.xcassets的图片资源
0 0
- imageNamed和imageWithContentsOfFile-无法加载图片的问题
- IOS图片加载方式:imageNamed和imageWithContentsOfFile的区别
- imageNamed与imageWithContentsOfFile加载图片的区别
- imageNamed与imageWithContentsOfFile加载图片的区别
- imageNamed与imageWithContentsOfFile加载图片的区别
- UIImage加载图片的方法及imageNamed和imageWithContentsOfFile的区别
- 使用imageNamed 与 imageWithContentsOfFile加载图片的区别
- 加载图片的三种方法imageNamed、imageWithContentsOfFile、NSData
- IOS如何选择图片加载方式:imageNamed和imageWithContentsOfFile的区别
- IOS如何选择图片加载方式:imageNamed和imageWithContentsOfFile的区别
- IOS如何选择图片加载方式:imageNamed和imageWithContentsOfFile的区别
- 【iOS开发】 iOS如何选择图片加载方式:imageNamed和imageWithContentsOfFile的区别
- imageNamed和imageWithContentsOfFile的区别
- 加载图片使用imageNamed方法还是 imageWithContentsOfFile?
- iOS加载图片imageNamed方法还是imageWithContentsOfFile
- 加载图片选择imageNamed 方法还是 imageWithContentsOfFile
- 对imageNamed和imageWithContentsOfFile的一些理解
- UIImageView关于imageNamed和imageWithContentsOfFile的区别
- PDF阅读器系列之--MuPDF源码分析过程(二)
- (java)根据map中value进行排序
- C++实验4—输出星号图
- 学习新语言
- PHP实现冒泡排序
- imageNamed和imageWithContentsOfFile-无法加载图片的问题
- A Knight's Journey(搜索题)
- Eclipse配置PyDev插件安装方法
- Bestcoder Pro.ID 2006 求奇数的乘积
- 深入理解C++中的mutable关键字
- C++ 常用类型转换的区别
- 记录为经典eclipse 添加java Web 开发插件地址
- 215. Kth Largest Element in an Array
- 类似支付宝 支付时候 的动画 Progress