原文地址::https://blog.csdn.net/hopedark/article/details/16115859#
相关文章
1、实现抠图&替换背景图----https://blog.csdn.net/poso123/article/details/79465478
2、iOS开发-简单图片背景替换(实现抠图效果)----https://blog.csdn.net/hitwhylz/article/details/41550411
3、iOS在图片上添加文字或图片----https://blog.csdn.net/glt_code/article/details/52711924
4、iOS图片拼接,图片文字合成总结----https://blog.csdn.net/YCM1101743158/article/details/73823250
5、iOS开发 在图片上添加文字,图片合成文字,图片上添加富文本,美图秀秀,美颜相机文字编辑----https://blog.csdn.net/horisea/article/details/70332486
本文分析对比了各种更改UIView背景的方法。当然,背景是根据一个图片来的(非纯色)。
一.加一个uiimageview在uiview上面
-
UIImageView* imageView = [[UIImageView alloc] initWithFrame:view.bounds];
-
imageView.image = [[UIImage imageNamed:@"name.png"] stretchableImageWithLeftCapWidth:left topCapHeight:top];
-
[view addSubview:imageView];
这种方式,如果原始图片大小不够(小于view的大小),可以拉伸,在view释放后也没有什么内存保留。
二.通过图片来生成UIColor设置view的backgroundColor
1.imageNamed方式
view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"name.png"]];
2.contentOfFile方式
-
NSString* path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"png"];
-
view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path];
这两种方式都会在生成color时占用大量的内存(原始图片的n倍,这个n可能会达到几千的程度)。而且如果图片大小不够,就会按照原始大小一个一个u画过去,也就是不会自动拉伸。1和2的区别在于,view释放后,1中的color并不会跟着释放,而是一直存在于内存中(当然,再次根据这个图片生成color时并不会再次申请内存了),而2中的color就会随着view的释放而释放。
三.quartzCore方式
-
UIImage *image = [UIImage imageNamed:@"name.png"];
-
view.layer.contents = (id) image.CGImage; // 如果需要背景透明加上下面这句
-
view.layer.backgroundColor = [UIColor clearColor].CGColor;
这种方式会自动拉伸图片,而且没有额外内存占用。
综上,推荐第三种方式来根据图片设置背景色。