UIVIewiOSiOS 程序员

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

2017-03-18  本文已影响3752人  Kobe_Dai

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

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];
用来实现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/

上一篇 下一篇

猜你喜欢

热点阅读