美文网首页
iOS 性能优化二

iOS 性能优化二

作者: 飞不越疯人院 | 来源:发表于2020-08-21 11:38 被阅读0次

主要讲解界面卡顿原因/优化方案/离屏渲染

iOS 性能优化一
iOS 性能优化二
iOS 性能优化三


1. 开发中遇到可能会造成卡顿的点

CPU部分:

  1. 对象的创建, 调整, 销毁;
  2. frame布局的计算, autolayout布局;
  3. 文本的计算和渲染;
  4. 图片的解码和绘制;

GPU部分:

  1. 纹理的渲染;
  2. 视图的混合;
  3. 图像的渲染;

2. 针对卡顿的一些优化方案

优化的宗旨就是尽量减少CPUGPU资源消耗;
2.1 CPU部分优化方案

  1. 使用轻量级的对象; 例如: 如果只是单纯的展示不需要处理事件, 考虑用CALayer替代UIView, 如果只是展示数字用int替代NSNumber;
  2. 不频繁修改UIView的相关属性, 尽量减少不必要的修改; 例如: frame, bound, transform等等;
  3. 提前计算好布局, 能一次性完成属性的调整就不要多次;
  4. Autolayoutframe方式耗费更多的CPU资源;(这个自己取舍吧 ,现在二者区分已经不大);
  5. 图片的size最好跟UIImageView的大小保持一致,不做图片的拉伸操作;例如: 如下代码如果设置一个1000*1000的图片, 则会进行图片的拉伸, 进而造成而外性能开销;
    [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    
  6. 控制线程的最大并发数量;
  7. 使用异步绘制和把耗时的操作放到子线程
    • 文本的尺寸计算和绘制;
    • 图片的解码绘制;

文本的计算和文本的绘制

#文本计算
[@"ABCDE" boundingRectWithSize:CGSizeMake(100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
#文本的绘制
[@"ABCDE" drawWithRect:CGRectMake(0, 0, 50, 50) options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
    

图片的解码和绘制, 如下代码imageNamed赋值左侧后其实并不是直接展示到屏幕上的,而是需要压缩图片的二进制数据, 然后再解码成屏幕可以识别的数据格(位图)式; 这个解码过程默认都是在主线程进行的;将这个过程放在子线程可以节省资源;

UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
imgV.image = [UIImage imageNamed:@"1.png"];

下面看下 SDWebImage中的解码方式, 通过看其源码可以查到在其下载图片后会进行压缩操作;

+ (UIImage *)decodedImageWithImage:(UIImage *)image {
    // while downloading huge amount of images
    // autorelease the bitmap context
    // and all vars to help system to free memory
    // when there are memory warning.
    // on iOS7, do not forget to call
    // [[SDImageCache sharedImageCache] clearMemory];
    
    if (image == nil) { // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error
        return nil;
    }
    
    @autoreleasepool{
        // do not decode animated images
        if (image.images != nil) {
            return image;
        }
        
        CGImageRef imageRef = image.CGImage;
        
        CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef);
        BOOL anyAlpha = (alpha == kCGImageAlphaFirst ||
                         alpha == kCGImageAlphaLast ||
                         alpha == kCGImageAlphaPremultipliedFirst ||
                         alpha == kCGImageAlphaPremultipliedLast);
        if (anyAlpha) {
            return image;
        }
        
        // current
        CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef));
        CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef);
        
        BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown ||
                                      imageColorSpaceModel == kCGColorSpaceModelMonochrome ||
                                      imageColorSpaceModel == kCGColorSpaceModelCMYK ||
                                      imageColorSpaceModel == kCGColorSpaceModelIndexed);
        if (unsupportedColorSpace) {
            colorspaceRef = CGColorSpaceCreateDeviceRGB();
        }
        
        size_t width = CGImageGetWidth(imageRef);
        size_t height = CGImageGetHeight(imageRef);
        NSUInteger bytesPerPixel = 4;
        NSUInteger bytesPerRow = bytesPerPixel * width;
        NSUInteger bitsPerComponent = 8;


        // kCGImageAlphaNone is not supported in CGBitmapContextCreate.
        // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
        // to create bitmap graphics contexts without alpha info.
        CGContextRef context = CGBitmapContextCreate(NULL,
                                                     width,
                                                     height,
                                                     bitsPerComponent,
                                                     bytesPerRow,
                                                     colorspaceRef,
                                                     kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast);
        // Draw the image into the context and retrieve the new bitmap image without alpha
        CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
        CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context);
        UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha
                                                         scale:image.scale
                                                   orientation:image.imageOrientation];
        
        if (unsupportedColorSpace) {
            CGColorSpaceRelease(colorspaceRef);
        }
        CGContextRelease(context);
        CGImageRelease(imageRefWithoutAlpha);
        return imageWithoutAlpha;
    }
}

2.1 GPU部分优化方案

  1. 尽量减少视图的数量; 这个没什么说的, 肯定是视图越少GPU绘制压力越小;
  2. 减少半透明的视图, 不透明的视图alpha就设置为1; 因为叠加半透明视图会增加额外绘制压力; 例如RGB 几个颜色半透明视图叠加会产生新的颜色就需要重新, 这会增加绘制压力;
  3. 避免出现离屏渲染;

3. 离屏渲染

不论是在屏渲染还是离屏渲染都是在GPU层面的;

  • 在屏渲染(On-Screen Rendering): 意为当前屏幕的渲染, 指的是GPU的渲染操作发生在当前用于显示的屏幕缓冲区中;
  • 离屏渲染(Off-Screen Rendering):意为GPU在当前屏幕缓冲区以外新开辟一个缓冲区进行操作;

为什么离屏渲染会额外耗费性能: 因为需要创建新的缓冲区, 另外离屏渲染的过程会频繁的切换上下文环境, 首先是要从当前屏幕On-Screen切换到离屏Off-Screen, 然后离屏渲染完成需要将离屏缓冲区的渲染结果放到屏幕上, 上下文环境需要再次切换到当前屏幕;
离屏渲染的操作

  1. 设置光栅化; self.layer.shouldRasterize = YES;
  2. 设置遮罩; layer.mask操作;分时图中的渐变色就是设置 mask 实现
  3. 设置圆角; 同时设置才会触发; 通过CoreGraphics绘制 圆角解决此问题;
      self.layer.masksToBounds = YES;
      self.layer.cornerRadius = 2;
    
  1. 设置阴影效果;以下之类的操作会离屏渲染;设置self.layer.shadowPath操作不会;
    self.layer.shadowColor = [UIColor redColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(4, 4);
    

文中测试代码
资料参考连接
iOS 保持界面流畅的技巧
iOS 视图渲染以及性能优化总结
iOS 图片的解码

相关文章

网友评论

      本文标题:iOS 性能优化二

      本文链接:https://www.haomeiwen.com/subject/gufsjktx.html