zl程序教程

您现在的位置是:首页 >  其他

当前栏目

IOS 图片解码性能优化

2023-04-18 14:55:28 时间

1.图片解码到底有多卡?

测试方法比较简单,在一个可以tableView里面展示图片,图片是已经放在本地的10张图片,每张图片大于1MB

代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BannerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BannerTableViewCell" forIndexPath:indexPath];
    
    // 获取图片
    NSInteger index = 0;
    index = indexPath.row%10;
    NSString *imageName = [NSString stringWithFormat:@"backImage%ld",(long)index];
    //UIImage *image = [UIImage imageNamed:imageName];
    NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    cell.contentImageView.image = image; 
    return cell;
}

细心的同学可能已经注意到了我在代码中写了两种方式加载图片。

一种是: UIImage imageNamed:imageName

一种是: UIImage imageWithContentsOfFile:path

后面我再解释为什么需要对比这两种加载方式,先上加载的结果吧。

1>使用UIImage imageWithContentsOfFile:path

image.png

2>使用UIImage imageNamed:imageName

image.png

两种方式都实际滑动一分钟, 可以清晰的看到,两种加载方式一开始都帧数很低,但是使用imageNamed:

的很快帧数就恢复到60帧,但是使用imageWithContentsOfFile:会一直卡顿,那是因为使用imageNamed:

会缓存图片,但是imageWithContentsOfFile: 则不会,而且 使用imageWithContentsOfFile:

出现了明显的卡顿,出现了明显的丢帧从曲线上来看能明显看到两种方式的差异问题。

再来解释我们使用的两种加载方式,使用 imageWithContentsOfFile:

实际上是模拟网络下载图片到本地后,再从本地加载展示图片的过程,imageNamed:方式则是模拟从Assets.xcassets

里加载图片的情况,可以明显看到苹果是对从Assets.xcassets 里加载图片做过优化的。

2.如何对图片解码部分进行优化

方案很简单:

解码的过程是可以直接放在子线程中的,解码完成后可以在主线程中将图片赋值给imageView.image并且缓存下来,下次再次查找到相同的图片直接在缓存中读取就可以了。

这个过程是不是听起来很熟悉,是的,这个过程已经有很有多的第三方库实现过了,其中最有名的就是SDWebImage了,SDWebImage的解码方法是decodedImageWithImage,使用了CGContextDrawImage,有兴趣的小伙伴们可以抽空去看看,在这我就不赘述了,直接上优化代码:

    [self queryImageCache:imageName block:^(UIImage *image) {
        cell.contentImageView.image = image;
    }];
- (void)queryImageCache:(NSString *)filename block:(void(^)(UIImage *image))block
{
    //从内存去取,如果没取到,就直接读取文件,在缓存起来
    UIImage *image = [self.memCache objectForKey:filename];
    if(image)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(block)
                block(image);
        });
    }
    else
    {
        //把解压操作放到子线程
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"jpg"];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            
            image = [UIImage decodedImageWithImage:image];
            [self.memCache setObject:image forKey:filename];
            // 同步主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                if(block)
                    block(image);
            });
       });
    }
}