iOS归纳

SDWebImage源码解析

2020-12-10  本文已影响0人  铁头娃_e245

作为iOS端最常用的三方库之一,该库提供了具有缓存支持的异步图像下载器

GitHub地址

特征


结构图

高层图

它的框架如下图所示,首先通过ImageView去通知View的Category,之后连接到Image Manager这个核心类,核心类分别管控着Image CacheImage Loader类,他们的底层实现基于Utils&CategoriesImage CoderImage Transformer

高层图
顶层API图

顶层API类图如下图,可以看到众多UIKit分类指向UIView(WebCache)类,之后指向Image Manager,这里可以看到整个API的逻辑处理非常清晰,最后都会调用到Image Manager类,后面的操作在由核心类分给其他类执行。

顶层API类图
总体类图

总体类图如下图,这里就不详细分析了,直接看后面源码解析


总体类图

基础用法

sd_setImageWithURL:

#import "UIImageView+WebCache.h"  //引用

//直接加载网络图片
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"]];   

sd_setImageWithURL: placeholderImage:

//先展示默认图片,当网络图片加载完成后替换
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"]];

sd_setImageWithURL: placeholderImage: options:

//先展示默认图片,并设置网络图片处理方式
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"] options:SDWebImageCacheMemoryOnly];

sd_setImageWithURL: placeholderImage: options: completed:

//展示默认图片,设置图片处理方式,以及执行图片加载完成后的block内部代码
[imageView sd_setImageWithURL:[NSURL URLWithString:@"url"] placeholderImage:[UIImage imageNamed:@"defaultImage"] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    NSLog(@"imageSize--height:%f,width:%f",image.size.height,image.size.width);
}];

其他还有多种不同功能api可以根据场景选用,这些API的区别就在于一些可选项
placeholder: 预览图
options: 选项,具体每个选项的详解可以看这里
completedBlock: 加载完成block回调

源码分析

阅读版本为5.10.0

首先,SDWebImage封装了系统类的Category(类别)为UIImageView+WebCacheNSButton+WebCache等等,让API使用起来更方便易用,如下图


所有的封装函数都会跳转到该类内部的sd_setImageWithURL: placeholderImage: options: progress: completed:中,之后经过多层跳转会进入UIView+WebCache类的sd_internalSetImageWithURL方法里,
上一篇 下一篇

猜你喜欢

热点阅读