iOS:切Label圆角的正确姿势

一、需求

我们会经常遇到这样一个需求,给TableViewCell添加标签,例如:饿了么App中店铺会有,减、特、新等标签,这些标签一般都是用UILabel控件实现,UILabel中设置text,textColor,backgroundColor,以及cornerRadius。


iOS:切Label圆角的正确姿势_第1张图片

问题

这个需求要求我们做圆角,业界也有很多做圆角的方式,最简单的就是设置:

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

但是这样做(label.layer.cornerRadius > 0 && label.layer.masksToBounds = YES)会出现离屏渲染,对于页面中只有少量需要做圆角,也不会造成卡顿,但是如果是每个TableViewCell设置一些圆角,就会使列表滑动起来有明显卡顿。

解决方法

业界对于圆角优化很多方式,大家可以搜一下相关文章。本文只针对UILabel的cornerRadius方式进行讲解。先说一下cornerRadius属性,它是影响layer显示的backgroundColor和border,对layer的contents不起作用。

  • 对于不需要设置label的backgroundColor,只设置borderWidth、borderColor的label,直接设置cornerRadius不需要设置masksToBounds = YES,就可以实现圆角功能。
  • 对于需要同时设置label的backgroundColor时,直接设置cornerRadius是不能正常显示圆角的,原因是:UILabel设置backgroundColor的行为,不再是设定layer的背景色而是为contents设置背景色。所以解决方式是我们不去设置label的backgroundColor,而是直接设置label.layer.backgroundColor,这样就可以实现单独设置cornerRadius,显示圆角的效果。

代码:

UILabel *tagLabel = [UILabel new];tagLabel.text = @"减";
tagLabel.textColor = [UIColor whiteColor];
tagLabel.font = [UIFont systemFontOfSize:12];
tagLabel.layer.backgroundColor = [UIColor greenColor].CGColor;
tagLabel.layer.cornerRadius = 2;

二、设置CALayer的mask,如UIImage

通过设置view.layer的mask属性,可以将另一个layer盖在view上,也可以设置圆角,但是mask同样会触发离屏渲染。

通过贝塞尔曲线生成,view中曲线描述的形状部分会被绘制出来。

    //通过贝塞尔曲线生成,【见下图】
    self.view.backgroundColor = [UIColor whiteColor];
    UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 250, 400)];
    imgView.center = self.view.center;
    imgView.image = [UIImage imageNamed:@"1.jpeg"];
    [self.view addSubview:imgView];
    
    //通过贝塞尔曲线生成
    CAShapeLayer * layer = [CAShapeLayer new];
    layer.path = [UIBezierPath bezierPathWithRoundedRect:imgView.bounds cornerRadius:50.f].CGPath;
   //layer.path = [UIBezierPath bezierPathWithOvalInRect:imgView.bounds].CGPath;
   //layer.path = [UIBezierPath bezierPathWithRoundedRect:imgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(50, 80)].CGPath;
    imgView.layer.mask = layer;

iOS:切Label圆角的正确姿势_第2张图片
CAShapeLayer生成的圆角

你还可以参考一下这篇文章

你可能感兴趣的:(iOS:切Label圆角的正确姿势)