UIImage方法的优化问题,当图片多时应该重写imageNamed方法

来源:互联网 发布:服务器租用网站源码 编辑:程序博客网 时间:2024/05/16 17:59

一、加载图片问题

UIImage image = [UIImage imageNamed:imageFileName];

这种图片加载方式带有图片缓存的功能,使用这种方式加载图片后,图片会自动加入系统缓存中,并不会立即释放到内存。一些资源使程序中经常使用的图片资源,

使用这种方式会加快程序的运行减少IO操作,但对于项目中只用到一次的图片,如果采用这种方案加载,会增导致程序的内存使用增加

以下为官方对此方法的解释说明:

imageNamed:

Returns the image object associated with the specified filename.

+ (UIImage *)imageNamed:( NSString *) name
Parameters
name

The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

Return Value

The image object for the specified file, or nil if the method could not find the specified image.

Discussion

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already

in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.


二、非缓存的加载方式

+ (UIImage *)imageWithContentsOfFile:(NSString *)path

+ (UIImage *)imageWithData:(NSData *)data


三、何时使用imageNamed方法


1、采用imageNamed方法的图片加载情况


图片资源反复使用到,如按钮背景图片的蓝色背景,这些图片要经常用到,而且占用内存少


2、不应该采用的情况:


(1)图片一般只使用一次,如一些用户的照片资源

(2)图片资源较大,加载到内存后,比较耗费内存资源

+ (UIImage *)imageNamed:( NSString *) name

{

return [self imageWithContentsOfFile:name]

 }

注意:当前版本的xcode要求把图片放在 image.xcassets中 ,而文件images.xcassets 里的文件是不在ipa包的根目录下的,这里的图都不是以图片格式存储在程序包里.而是以文件形式储存在Assets.car文件中,所以是不存在文件目录的。

放在其中的图片,可以通过imageName直接访问。但是不能通过imageContentsOfFile访问。

所以如果需要使用imageContentsOfFile,则需要把图片包单独写个group存放,而不是放在images.xcassets中。

1 0
原创粉丝点击