ImagePipeline是Fresco读取数据的整个调度系统,作为一个图片加载组件,主要工作流程为:
- 检查内存缓存
- 检查磁盘缓存
- 文件读取或网络请求,并存储到各个缓存。
官方流程图如下:
这和主要的图片加载逻辑基本类似,既然如此,那我们就从图片加载组件最主要的两个方面入手分析源码:
1) 如何自定义缓存线程和加载线程的配置;
2) 缓存设计算法。
首先看第一个问题,要看ImagePipeline的配置,我们来分析一下ImagePipelineConfig的源码:
ImagePipeline的可配置项如下:
ImagePipeline用到了三个缓存,首先是DiskCache,然后还有两个MemoryCache,分别是保存已解码Bitmap的和保存EncodedImage的缓存。Fresco将未解码的原始数据也进行了内存缓存,然后根据是否旋转或者缩放以及解码质量进行解码成bitmap存放内存空间,其实在我所接触的应用场景中这部分内容其实是不太需要的,因为一张图片基本上只在一个地方使用,即使多处使用也不太需要这么复杂的变换,可能Fresco想的比较周到吧。
内存缓存使用的是通用的lru算法(最近最少使用原则),内存缓存的设计代码在CountingMemoryCache,CountingMemoryCache是一个基于LRU策略来管理缓存中元素的一个类,它实现的trim()方法可以根据Type的不同来采取不同策略的回收为:
Fresco使用的黑科技还有很多,它是一份巨大的宝藏等着挖掘,我只是粗浅的总结了部分我get到的点,以后进一步深入学习中再和大家分享。