iOS UIView性能最优的设计圆角并且绘制边框颜色

在最新的版本迭代里,UI想给UICollectionViewCell切成圆角并且要有色边框,以那种卡片形式展现给用户,iOS里有好几种方法可以实现给view设计圆角并绘制边框颜色,这篇文章里会给出我认为性能最优的一个方法,最终效果如下:

iOS UIView性能最优的设计圆角并且绘制边框颜色_第1张图片
WechatIMG108.jpeg

方法一

最常见设计圆角,绘制边框的方法是利用CALayercornerRadiusborderWidth, borderColor来实现:

self.view.layer.maskToBounds = YES;
self.view.layer.cornerRadius = 4.f;
self.view.layer.borderWidth = 2.f;
self.view.layer.borderColor = [UIColor redColor].CGColor;

这个实现方法里maskToBounds会触发离屏渲染(offscreen rendering),会导致app的FPS下降,特别是给UICollectionViewCell设计圆角的时候,用户滑动浏览时,会觉得明显的卡顿,用户体验非常不好,所以在给多个view设计圆角的时候不建议使用

方法二

使用四张图片分别放在view的四角,或者拉伸一张四边圆角的图片实现圆角,不建议,方法太傻X

方法三

这个方法,是我在使用并推荐的一个。废话不多,直接上代码:

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
  • 先看代码中创建的贝塞尔曲线,通过UIBezierPathbezierPathWithRoundedRect:cornerRadius:方法来绘制出一个带圆角矩形的路径,用来给CAShapeLayer绘制图形
  • 第一个layer叫做maskLayer,是用来给cell实现遮罩效果,因为layer使用的path是一个圆角矩形的贝塞尔曲线,那么这个layer形成的遮罩可以实现cell的圆角
  • 第二个layer叫做borderLayer,是用来绘制cell边框颜色的,通过CAShapeLayerlineWidth, strokeColor来绘制边框,注意fillColor一定要设置成clearColor,否则会挡住整个cell
  • 最后,将borderLayer加载到cell的layer上,将maskLayer设置成cell layer的mask
用来实现UICollectionViewCell圆角并绘制边框颜色的完整代码如下:
- (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];
}

转载请注明出处,原文地址:http://kobedai.me/p9rsts-6l/

你可能感兴趣的:(iOS UIView性能最优的设计圆角并且绘制边框颜色)