先上代碼
- (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)建了兩個CAShapeLayer, 關(guān)于CAShapeLayer先講幾句,CAShapeLayer屬于Core Animation框架,會通過GPU來渲染圖形,節(jié)省性能,動畫渲染直接交給手機(jī)GPU,不消耗內(nèi)存。CAShapeLayer中shape是形狀的意思,需要形狀才能生效,而貝塞爾曲線恰恰可以為CAShapeLayer提供路徑,CAShapeLayer在提供的路徑中進(jìn)行渲染繪制出了shape
- 先看代碼中創(chuàng)建的貝塞爾曲線,通過UIBezierPath的bezierPathWithRoundedRect:cornerRadius:方法來繪制出一個帶圓角矩形的路徑,用來給CAShapeLayer繪制圖形
- 第一個layer叫做maskLayer,是用來給cell實(shí)現(xiàn)遮罩效果,因?yàn)閘ayer使用的path是一個圓角矩形的貝塞爾曲線,那么這個layer形成的遮罩可以實(shí)現(xiàn)cell的圓角
- 第二個layer叫做borderLayer,是用來繪制cell邊框顏色的,通過CAShapeLayer的lineWidth, strokeColor來繪制邊框,注意fillColor一定要設(shè)置成clearColor,否則會擋住整個cell
- 最后,將borderLayer加載到cell的layer上,將maskLayer設(shè)置成cell layer的mask