iOS:切Label圆角的正确姿势

一、需求

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


问题

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

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;

CAShapeLayer生成的圆角

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,595评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,152评论 5 13
  • 转载://www.greatytc.com/p/32fcadd12108 每个UIView有一个伙伴称为l...
    F麦子阅读 6,353评论 0 13
  • 每个UIView有一个伙伴称为layer,一个CALayer。UIView实际上并没有把自己画到屏幕上;它绘制本身...
    shenzhenboy阅读 3,164评论 0 17
  • 最近看到一句话:“以前是屯书,现在是屯课!”——知识付费越来越被大众所接受,有的人甚至报名参加各种课程,忙不自暇,...
    Sunny_guyue阅读 260评论 0 0