UIView显示图片高级技巧

一、加一个UIImageview在UIView上(可以)

UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
imageView.image = [UIImage imageNamed:@"home"];
[self.view addSubview:imageView];

这种方式,原始图片大小不够(小于view的大小),会拉伸图片,让图片失真,view释放后也不会有什么内存保留。

二、通过图片来生成UIColor来设置UIView的背景色。注意是根据图片来生成color(不推荐)

1 . imageName方式:
如果图片较小,并且频繁使用的图片,使用imageName:来加载图片(按钮图片/主页图片/占位图)

self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"home"]]; 

2 . contentOfFile方式:
如果图片较大,并且使用次数较少,使用 imageWithContentOfFile:来加载(相册/版本新特性)

NSString *path = [[NSBundle mainBundle]pathForResource:@"name" ofType:@"png"];  
    self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path]]; 

以上两种方式都会在生成color的时候消耗大量的内存(原始图片的N倍,这个N可能会达到几千的程度,而且如果原始图片大小不够,就会按照原始大小一个一个U画过去,是不会自动拉伸的。1和2的区别:1中的color不会随着View的释放而释放,而是一直存在于内存中。(再次根据这个图片生成Color的时候,不会再次去申请内存)。而2中的color会随着View的释放而释放。

三、quarCore方式(推荐)

UIImage *image = [UIImage imageNamed:@"3549"];
//推荐这样创建image对象:UIImage *image = [UIImage imageWithContentsOfFile:path];
self.view.layer.contents = (id)image.CGImage;
//背景透明加上这一句
self.view.layer.backgroundColor = [UIColor clearColor].CGColor;

在显示简单的单张图片时,利用 UIView.layer.contents 就足够了,没必要使用 UIImageView 带来额外的资源消耗。

如果对性能优化感兴趣的小伙伴,可以移步这里http://blog.csdn.net/biyuhuaping/article/details/78606226

猜你喜欢

转载自blog.csdn.net/biyuhuaping/article/details/78614335
今日推荐