先上代碼
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
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 = lineColor.CGColor;
borderLayer.fillColor = [UIColor clearColor].CGColor;
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, cellWidth, cellHeight) cornerRadius:cornerRadius];
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ì)通過GPU來渲染圖形页畦,節(jié)省性能,動(dòng)畫渲染直接交給手機(jī)GPU,不消耗內(nèi)存棚赔。CAShapeLayer中shape是形狀的意思,需要形狀才能生效徘郭,而貝塞爾曲線恰恰可以為CAShapeLayer提供路徑靠益,CAShapeLayer在提供的路徑中進(jìn)行渲染繪制出了shape
- 先看代碼中創(chuàng)建的貝塞爾曲線,通過UIBezierPath的bezierPathWithRoundedRect:cornerRadius:方法來繪制出一個(gè)帶圓角矩形的路徑残揉,用來給CAShapeLayer繪制圖形
- 第一個(gè)layer叫做maskLayer胧后,是用來給cell實(shí)現(xiàn)遮罩效果,因?yàn)閘ayer使用的path是一個(gè)圓角矩形的貝塞爾曲線抱环,那么這個(gè)layer形成的遮罩可以實(shí)現(xiàn)cell的圓角
- 第二個(gè)layer叫做borderLayer壳快,是用來繪制cell邊框顏色的,通過CAShapeLayer的lineWidth, strokeColor來繪制邊框镇草,注意fillColor一定要設(shè)置成clearColor眶痰,否則會(huì)擋住整個(gè)cell
- 最后,將borderLayer加載到cell的layer上梯啤,將maskLayer設(shè)置成cell layer的mask