一、加载图片的几种方法
1.用imageNamed方法
[UIImage imageNamed:ImageName];
利用它可以方便加载资源图片。用imageNamed的方式加载时,会把图像数据根据它的名字缓存在系统内存中,以提高imageNamed方法获得相同图片的image对象的性能。即使生成的对象被 autoReleasePool释放了,这份缓存也不释放。而且没有明确的释放方法。如果图像比较大,或者图像比较多,用这种方式会消耗很大的内存。
2.用 imageWithContentsOfFile 方法
NSString *thumbnailFile = [NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], fileName];UIImage *thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
利用这种方法加载的图片是不会缓存的。得到的对象时autoRelease的,当autoReleasePool释放时才释放。
3.用initWithContentsFile方法
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
利用这种方法要手动release掉。不系统缓存。release后立即释放,一般用在封面等图比较大的地方。
二、方法实现(分类)
.h文件
#import <UIKit/UIKit.h>
@interface UIImage (JooImage)
+(UIImage*)JooImageNamed: (NSString*)imageName;
@end
.m文件
#import "UIImage+JooImage.h"
#import <objc/runtime.h>
#import <objc/message.h>
@implementation UIImage (JooImage)
// load 在初始化类时调用,每个类都有一个load 方法,
// 类的初始化先于对象
+(void)load
{
//以下方法就告诉系统用后面的方法替换前面的
method_exchangeImplementations(class_getClassMethod(self, @selector(imageNamed:)),
class_getClassMethod(self, @selector(myImageNamed:)));
}
+(UIImage*)JooImageNamed:(NSString *)imageName
{
// 图片要支持jpg 和png
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"png"];
if (path == nil)
{
path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"];
}
// 这里image 在回收后不会占用cash 内存
UIImage *image = [UIImage imageWithContentsOfFile:path];
return image;
}
@end
网友评论