优雅的为cell设计圆角并绘制边框颜色

先上代码

- (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];
}

具体解释如下:

  • 代码中创建了两个CAShapeLayer, 关于CAShapeLayer先讲几句,CAShapeLayer属于Core Animation框架,会通过GPU来渲染图形,节省性能,动画渲染直接交给手机GPU,不消耗内存。CAShapeLayer中shape是形状的意思,需要形状才能生效,而贝塞尔曲线恰恰可以为CAShapeLayer提供路径,CAShapeLayer在提供的路径中进行渲染绘制出了shape
  • 先看代码中创建的贝塞尔曲线,通过UIBezierPath的bezierPathWithRoundedRect:cornerRadius:方法来绘制出一个带圆角矩形的路径,用来给CAShapeLayer绘制图形
  • 第一个layer叫做maskLayer,是用来给cell实现遮罩效果,因为layer使用的path是一个圆角矩形的贝塞尔曲线,那么这个layer形成的遮罩可以实现cell的圆角
  • 第二个layer叫做borderLayer,是用来绘制cell边框颜色的,通过CAShapeLayer的lineWidth, strokeColor来绘制边框,注意fillColor一定要设置成clearColor,否则会挡住整个cell
  • 最后,将borderLayer加载到cell的layer上,将maskLayer设置成cell layer的mask
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容