UIView设置图片-不使用UIImageView

昨天看到一个面试题,是在UIView上面添加一张图片,但是不使用UIImageview。目前我就想到了两种方式。

1、将图片作为UIView的背景色。(不推荐使用)

这种方式会在生成color时占用大量的内存。如果图片大小不够,就会平铺多张图片,不会去拉伸图片以适应View的大小。

 self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageNamed:@"image.jpg"]];//方式一

 NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"png"];
 self.view.backgroundColor = [UIColorcolorWithPatternImage:[UIImageimageWithContentsOfFile:path]];方式二

在View释放后,1中的color不会跟着释放,而是一直存在内存中;2中的color会跟着释放掉,当然再次生成color时就会再次申请内存

2、绘制图片路径,添加到layer上

NSString *path = [[NSBundlemainBundle]pathForResource:@"image"ofType:@"png"];   
UIImage *image = [UIImageimageWithContentsOfFile:path];
self.view.layer.contents = (id)image.CGImage;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容