圆角设置方式
cornerRadius
适用于需要设置圆角且元素不多的情况下(页面中仅仅几个按钮、图片)。
UIView *view = [[UIView alloc]init];
view.backgroundColor = [UIColor orangeColor];
view.frame = CGRectMake(100,100,200,200);
view.layer.cornerRadius = view.frame.size.width/2;
view.layer.masksToBounds = YES;
[self.view addSubview:view];
如果只是设置了cornerRadius并不会触发离屏渲染。设置maskToBounds会导致离屏渲染,导致性能下降。触发离屏渲染会增加内存消耗。如果在UITableView cell中添加过多的圆角控件,则会导致滑动帧数骤降。需要修改上面代码。
UIView *view = [[UIView alloc]init];
view.backgroundColor = [UIColor orangeColor];
view.frame = CGRectMake(100,100,200,200);
view.layer.cornerRadius = view.frame.size.width/2;
view.layer.masksToBounds = YES;
view.layer.shouldRasterize = YES;
view.layer.rasterizationScale =[UIScreen mainScreen].scale;
[self.view addSubview:view];
shouldRasterize = YES 设置光栅化之后,会将首次离屏渲染的结果以位图(bitmap)的形式缓存到内存中,再次使用的时候直接使用缓存,节省了离屏渲染损耗的性能。
P.s.
如果layer及sublayers经常改变的话,它就会一直不停的渲染及删除缓存重新创建缓存,这种情况下建议不要使用光栅化,这样也是比较耗费性能的。
重写drawRect
通过重写drawRect方法也可以实现圆角方法。缺点内存占用会增多、效率也会变低。
UIBezierPath + CAShapeLayer
新建图层并重绘图层路径。使用CAShapeLayer动画渲染直接由GPU负责,相比于重写drawRect方法使用CPU渲染,效率会很高、内存消耗也会减少。
UIView *view = [[UIView alloc]init];
view.frame = CGRectMake(100,100,200,200);
view.backgroundColor = [UIColor orangeColor];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:view.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
[self.view addSubview:view];
图片遮盖
做一张和控件背景颜色相同的,中部为透明的所需形状的图片,直接覆盖在已有控件上。GPU对于多层混合渲染也会消耗一些性能。但是比离屏渲染所消耗的性能要低。