iOS 大量圆角的使用影响性能问题

来源:互联网 发布:海王星股票交易软件 编辑:程序博客网 时间:2024/05/23 00:01

iOS设备的硬件时钟会发出Vsync(垂直同步信号),然后App的CPU会去计算屏幕要显示的内容,之后将计算好的内容提交到GPU去渲染。随后,GPU将渲染结果提交到帧缓冲区,等到下一个VSync到来时将缓冲区的帧显示到屏幕上。也就是说,一帧的显示是由CPU和GPU共同决定的。


ios_frame_drop.png


从上图可以看出,第三个Vsyc到来时GPU还没有渲染好,这一帧就会被丢弃,等待下一次机会,此时屏幕上显示的还是之前的内容,这就是界面卡顿的原因。也就是说,不管GPU还是CPU阻碍了显示的流程,都会造成掉帧的现象。
我们在绘制圆角时经常会用到layer的属性:

 _view1.layer.cornerRadius = 10; _view1.layer.masksToBounds = YES;

CALayer的border,cornerRadius,阴影,mask,通常会触发离屏渲染(offscreen rendering),而离屏渲染通常发生在GPU中,当一个列表中有大量的圆角使用calayer并快速滑动时,可以观察到GPU的资源已经占满,而CPU的资源消耗很少。这时界面的帧数会降低,会有卡顿的情况。
为了避免这种情况,可以尝试开启CALayer.shouldRasterize属性,这会把原本离屏渲染的操作转嫁到CPU上。也可以把一张已经绘制好的圆角图片覆盖到原本的视图上。最彻底的解决办法是,把需要显示的图形在后台线程绘制为图片,避免使用CALayer的属性。
我用collectionviewcell的CALayer绘制圆角,在真机上滑动列表测的时候有明显的卡顿。

    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];    UIImageView * view = [cell viewWithTag:1000];    if (!view) {        view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];        [cell addSubview:view];        view.tag = 1000;        view.backgroundColor = [UIColor redColor];        view.image = [UIImage imageNamed:@"qq"];        view.layer.cornerRadius = 10;        view.layer.masksToBounds = YES;    }   return cell;

屏幕快照 2017-02-07 下午3.00.26.png

不使用calayer,对image进行裁剪,滑动列表不再卡顿:

    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];    UIImageView * view = [cell viewWithTag:1000];    if (!view) {        view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];        [cell addSubview:view];        view.tag = 1000;        dispatch_queue_t backQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);        dispatch_async(backQueue, ^{            UIImage * image = [self cutCircleImageWithImage:[UIImage imageNamed:@"qq"] size:view.frame.size radious:10];            dispatch_async(dispatch_get_main_queue(), ^{                view.image = image;            });        });    }    return cell;
- (UIImage *)cutCircleImageWithImage:(UIImage *)image size:(CGSize)size radious:(CGFloat)radious {    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);    CGRect rect = CGRectMake(0, 0, size.width, size.height);    CGContextAddPath(UIGraphicsGetCurrentContext(),                     [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radious].CGPath);    CGContextClip(UIGraphicsGetCurrentContext());    [image drawInRect:rect];    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return newImage;}

屏幕快照 2017-02-07 下午2.45.06.png
原创粉丝点击