優(yōu)雅的為cell設(shè)計圓角并繪制邊框顏色

先上代碼

- (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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容