UIView切圆角

前言

切圆角是我们开发中经常遇到的需求,实现方式也有很多种,其中最常见的实现方式是:

label.layer.cornerRadius = 5.0; 
label.layer.masksToBounds = YES; 

但是这样做(label.layer.cornerRadius > 0 && label.layer.masksToBounds = YES)会出现离屏渲染。对于页面中只有少量需要做圆角的情况,可能不会导致性能问题,但是如果在一个长列表页这样去切大量圆角,就会导致列表滑动起来有明显卡顿。

切圆角优化

对视图圆角实现方式的优化方法有很多种,这里介绍我经常用的cornerRadius优化方式。
既然cornerRadius和masksToBounds同时设置会导致离屏渲染,那么不同时设置它们不就好了嘛?这里涉及到cornerRadius属性的作用。

cornerRadius属性会影响layer显示的backgroundColor和border,但对layer的contents不起作用。

所以,就有下面的两种优化方式:

  1. 对于只有边框,没有背景色的控件设置圆角,只设置cornerRadius,不用设置masksToBounds = YES,其实就可以实现圆角功能;
label.layer.cornerRadius = 5.0;
label.layer.borderWidth = 1.0;
label.layer.borderColor = [UIColor blackColor].CGColor;
image1.PNG
  1. 对有背景色的控件切圆角,只设置cornerRadius是不会实现圆角效果的,因为控件的背景色设置的是layer的contents的背景色,而不是layer的背景色。因此,解决办法就是:不要设置控件的backgroundColor,而是去设置layer的backgroundColor。
label.layer.cornerRadius = 5.0;
label.layer.backgroundColor = [UIColor brownColor].CGColor;
image2.PNG

你可能感兴趣的:(UIView切圆角)