iOS UIImage加载图片的问题

来源:互联网 发布:java base64 aes加密 编辑:程序博客网 时间:2024/04/27 14:45

[UIImage imageNamed:@"icon.png"]

用上面的方法加载图片有问题。该方法即可以从bundle中读取图片。

这种方法在application bundle的顶层文件夹寻找由供应的名字的图象 。
如果找到图片,装载到iPhone系统缓存图象。那意味图片是(理论上)放在内存里作为cache的。因此如果图片资源多了或大了,此方式容易引起发生内存警告从而导致自动退出的问题。

最好是通过直接读取文件路径[UIImage imageWithContentsOfFile]解决掉这个问题,应用示例:

NSString *path = [[NSBundle mainBundle] pathForResource:@”icon” ofType:@”png”];
myImage = [UIImage imageWithContentsOfFile:path];


备注:imageNamed方法是不能通过路径进行加载图片的,如果要通过路径加载图片可以通过下面两个方法加载,一个是URL一个是FilePath。

NSImage *image = [[NSImage alloc]initWithContentsOfURL:(NSURL *)];NSImage *image = [[NSImage alloc]initWithContentsOfFile:(NSString *)];

一、加载图片问题

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)图片资源较大,加载到内存后,比较耗费内存资源

0 0
原创粉丝点击