1.方式一:
最常見(jiàn)設(shè)計(jì)圓角,繪制邊框的方法是利用CALayer的cornerRadius和borderWidth, borderColor來(lái)實(shí)現(xiàn):
self.view.layer.maskToBounds = YES;
self.view.layer.cornerRadius = 4.f;
self.view.layer.borderWidth = 2.f;
self.view.layer.borderColor = [UIColor redColor].CGColor;
這個(gè)實(shí)現(xiàn)方法里maskToBounds會(huì)觸發(fā)離屏渲染(offscreen rendering),會(huì)導(dǎo)致app的FPS下降,特別是給UICollectionViewCell設(shè)計(jì)圓角的時(shí)候,用戶滑動(dòng)瀏覽時(shí),會(huì)覺(jué)得明顯的卡頓,用戶體驗(yàn)非常不好,所以在給多個(gè)view設(shè)計(jì)圓角的時(shí)候不建議使用。
2.方式二:
直接上代碼
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cell isKindOfClass:[GXSectionCell class]]) {
CGFloat cellWidth = cell.width;
CGFloat cellHeight = cell.height;
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = CGRectMake(0, 0, cellWidth, cellHeight);
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.frame = CGRectMake(0, 0, cellWidth, cellHeight);
borderLayer.lineWidth = 1.f;
borderLayer.strokeColor = [UIColor colorWithHexString:@"D2D2D2"].CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(KNormalSpace, KNormalSpace/4, cellWidth - 2 * KNormalSpace, cellHeight - KNormalSpace/2) cornerRadius:5.0f];
maskLayer.path = bezierPath.CGPath;
borderLayer.path = bezierPath.CGPath;
[cell.contentView.layer insertSublayer:borderLayer atIndex:0];
[cell.layer setMask:maskLayer];
}
}
- 代碼中創(chuàng)建了兩個(gè)
CAShapeLayer, 關(guān)于CAShapeLayer先講幾句,CAShapeLayer屬于Core Animation框架,會(huì)通過(guò)GPU來(lái)渲染圖形,節(jié)省性能,動(dòng)畫渲染直接交給手機(jī)GPU,不消耗內(nèi)存。CAShapeLayer中shape是形狀的意思,需要形狀才能生效,而貝塞爾曲線恰恰可以為CAShapeLayer提供路徑,CAShapeLayer在提供的路徑中進(jìn)行渲染繪制出了shape - 先看代碼中創(chuàng)建的貝塞爾曲線,通過(guò)
UIBezierPath的bezierPathWithRoundedRect:cornerRadius:方法來(lái)繪制出一個(gè)帶圓角矩形的路徑,用來(lái)給CAShapeLayer繪制圖形 - 第一個(gè)layer叫做
maskLayer,是用來(lái)給cell實(shí)現(xiàn)遮罩效果,因?yàn)?code>layer使用的path是一個(gè)圓角矩形的貝塞爾曲線,那么這個(gè)layer形成的遮罩可以實(shí)現(xiàn)cell的圓角。 - 第二個(gè)
layer叫做borderLayer,是用來(lái)繪制cell邊框顏色的,通過(guò)CAShapeLayer的lineWidth,strokeColor來(lái)繪制邊框,注意fillColor一定要設(shè)置成clearColor,否則會(huì)擋住整個(gè)cell - 最后,將
borderLayer加載到cell的layer上,將maskLayer設(shè)置成cell layer的mask。