Bootstrap

iOS开发 SDWebImage加载webp动图以及加载大量动图

 先在项目中集成

pod 'SDWebImage

pod 'SDWebImageWebPCoder'

 SDWebImageWebPCoder是针对webp的解码器。在大多数情况下加载网络图片都是使用SDWebImage来实现。但是对于webp图的话就要加多一个解码器SDWebImageWebPCoder。

示例大部分加载网络图片的实现
 

//大小自己设置
UIImageView *imageView = [[UIImageView alloc] init];
imageView = UIViewContentModeScaleAspectFill;
[self addSubview: imageView];

//加载图片,耗时大概几毫秒的样子
imageView sd_setImageWithURL:<普通图片链接> placeholderImage:nil options:SDWebImageHighPriority completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];


//加载webp链接,耗时一秒左右
imageView sd_setImageWithURL:< webp链接> placeholderImage:nil options:SDWebImageHighPriority completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];

你可以先对比一下加载这两个图片的耗时的区别。UIImageView加载普通图片是挺快的,但是加载webp图就会很慢,慢的离谱,200kb左右的webp动图,加载耗时在1秒左右,是不是很慢。

我的项目需要CollectView加载大量的动图,使用上述的方式就会给人一种非常非常卡顿的感觉,体验非常不好。这篇文章也是想记录一下这个。

 

CollectView或tableview加载大量动图卡顿加载慢的问题

在cell即将显示的再加载资源,在cell从页面中移除的时候取消加载图片的任务,在cell复用的时候将Image置为nil。
 

//cell即将显示,加载图片
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{

  [cell.imageView sd_setImageWithURL:ossImageUrl placeholderImage:nil options:SDWebImageHighPriority completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
    }];

}

// Cell 完全离开屏幕时触发。当一个 Cell 被从屏幕上移除
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(HSImageCollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    //取消加载图片的任务
    [cell.imageView sd_cancelCurrentImageLoad];
}


//在你自定义cell的内部加上
- (void)prepareForReuse{
    [super prepareForReuse];
    
    [self.imageView sd_cancelCurrentImageLoad];
    self.imageView.image = nil; // 释放图片
}

这样处理之后加载图片是没问题的,但是加载webp还是卡顿。 

看了一下发现SDWebImage是有一个SDAnimatedImageView完全继承UIImageView的组件。使用SDAnimatedImageView来加载webp动图就流程很多啦。

;