一、在uiview上添加一个uiimageview,这种方式,如果原始图片大小不够(小于view的大小),可以拉伸,在view释放后也没有什么内存保留。
UIImageView* imageView = [[UIImageView alloc] initWithFrame:view.bounds];
imageView.image = [[UIImage imageNamed:@"name.png"] stretchableImageWithLeftCapWidth:left topCapHeight:top];
[view addSubview:imageView];
二、通过view的backgroundColor进行设置,这两种方式都会在生成color时占用大量的内存(原始图片的n倍,这个n可能会达到几千的程度)。而且如果图片大小不够,就会按照原始大小一个一个u画过去,也就是不会自动拉伸。1和2的区别在于,view释放后,1中的color并不会跟着释放,而是一直存在于内存中(当然,再次根据这个图片生成color时并不会再次申请内存了),而2中的color就会随着view的释放而释放。
1、imageNamed方式
UIColor *Colors =[UIColor colorWithPatternImage:[UIImage imageNamed:@"BluePoint"]];
self.view.backgroundColor = Colors;
2、contentOfFile方式
NSString* path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"png"];
view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path];
三、quartzCore方式,这种方式会自动拉伸图片,而且没有额外内存占用。
UIImage *image = [UIImage imageNamed:@"name.png"];
view.layer.contents = (id) image.CGImage; // 如果需要背景透明加上下面这句
view.layer.backgroundColor = [UIColor clearColor].CGColor;
综上,推荐第三种方式来根据图片设置背景色。
如果需要降uiview的四个角全部设置成圆角,只需设置其layer的cornerRadius属性即可(项目雪瑶添加QuartzCore框架)。而要制定某几个角为圆角的话,这种方法就不好用了。
下边说一种简单而优雅的方案:
代码如下:
UIView*view2=[[UIViewalloc]initWithFrame:CGRectMake(120,10,80,80)];
view2.backgroundColor=[UIColorredColor];
[self.viewaddSubview:view2];
UIBezierPath*maskPath=[UIBezierPathbezierPathWithRoundedRect:view2.boundsbyRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRightcornerRadii:CGSizeMake(10,10)];
CAShapeLayer*maskLayer=[[CAShapeLayeralloc]init];
maskLayer.frame=view2.bounds;
maskLayer.path=maskPath.CGPath;
view2.layer.mask=maskLayer;
其中粗体:
byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
指定了需要成为圆角的角,该参数是UIRectCorner类型的,可选的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
使用“|”来组合就可以了
其中标红:
CGSizeMake(10,10)
设置圆角的大小,Max为uiview的Min边长的一半,超过Max的值效果就不再变。
效果图如下: