一、需求
我們會(huì)經(jīng)常遇到這樣一個(gè)需求纠脾,給TableViewCell添加標(biāo)簽,例如:餓了么App中店鋪會(huì)有蜕青,減苟蹈、特、新等標(biāo)簽右核,這些標(biāo)簽一般都是用UILabel控件實(shí)現(xiàn)慧脱,UILabel中設(shè)置text,textColor贺喝,backgroundColor菱鸥,以及cornerRadius。
問(wèn)題
這個(gè)需求要求我們做圓角躏鱼,業(yè)界也有很多做圓角的方式氮采,最簡(jiǎn)單的就是設(shè)置:
label.layer.cornerRadius = 2;
label.layer.masksToBounds = YES;
但是這樣做(label.layer.cornerRadius > 0 && label.layer.masksToBounds = YES)會(huì)出現(xiàn)離屏渲染,對(duì)于頁(yè)面中只有少量需要做圓角染苛,也不會(huì)造成卡頓鹊漠,但是如果是每個(gè)TableViewCell設(shè)置一些圓角,就會(huì)使列表滑動(dòng)起來(lái)有明顯卡頓。
解決方法
業(yè)界對(duì)于圓角優(yōu)化很多方式断序,大家可以搜一下相關(guān)文章纺腊。本文只針對(duì)UILabel的cornerRadius方式進(jìn)行講解。先說(shuō)一下cornerRadius屬性娶靡,它是影響layer顯示的backgroundColor和border牧牢,對(duì)layer的contents不起作用。
- 對(duì)于不需要設(shè)置label的backgroundColor姿锭,只設(shè)置borderWidth塔鳍、borderColor的label,直接設(shè)置
cornerRadius
艾凯,不需要設(shè)置masksToBounds = YES献幔,就可以實(shí)現(xiàn)圓角功能。
- 對(duì)于需要同時(shí)設(shè)置label的backgroundColor時(shí)趾诗,直接設(shè)置cornerRadius是不能正常顯示圓角的蜡感,原因是:UILabel設(shè)置backgroundColor的行為,不再是設(shè)定layer的背景色而是為contents設(shè)置背景色恃泪。所以解決方式是我們不去設(shè)置label的backgroundColor郑兴,而是直接設(shè)置label.layer.backgroundColor,這樣就可以實(shí)現(xiàn)單獨(dú)設(shè)置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;
二、設(shè)置CALayer的mask览效,如UIImage
通過(guò)設(shè)置view.layer的mask屬性却舀,可以將另一個(gè)layer蓋在view上,也可以設(shè)置圓角锤灿,但是mask同樣會(huì)觸發(fā)離屏渲染挽拔。
通過(guò)貝塞爾曲線生成,view中曲線描述的形狀部分會(huì)被繪制出來(lái)但校。
//通過(guò)貝塞爾曲線生成螃诅,【見下圖】
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];
//通過(guò)貝塞爾曲線生成
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;
你還可以參考一下這篇文章