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

2017-05-01  本文已影响0人  为什么划船不靠桨

先上代码

- (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
上一篇 下一篇

猜你喜欢

热点阅读