Glide分析
一、Glide用法及介紹
1.1 什么是Glide?
Glide是一個加載圖片的庫,作者是bumptech,它是在泰國舉行的google 開發者論壇上google為我
們介紹的,這個庫被廣泛的運用在google的開源專案中,
1.2 Glide解決什么問題?
Glide是一個非常成熟的圖片加載庫,他可以從多個源加載圖片,如:網路,本地,Uri等,更重要的
是他內部封裝了非常好的快取機制并且在處理圖片的時候能保持一個低的記憶體消耗,

1. 3 Glide的優缺點
1.3.1 優點
1.多樣化媒體加載
Glide 不僅是一個圖片快取,它支持 Gif、WebP、縮略圖,甚至是 Video
2. 生命周期集成
通過設定系結生命周期,我們可以更加高效的使用Glide提供的方式進行系結,這樣可以更好的讓
加載圖片的請求的生命周期動態管理起來
**3.**高效的快取策略
A. 支持Memory和Disk圖片快取
B. Picasso 只會快取原始尺寸的圖片,而 Glide 快取的是多種規格,也就意味著 Glide 會根據你
ImageView 的大小來快取相應大小的圖片尺寸
比如你 ImageView 大小是200200,原圖是 400400 ,而使用 Glide 就會快取 200200 規格的圖,
而 Picasso 只會快取 400400 規格的,這個改進就會導致 Glide 比 Picasso 加載的速度要快,畢竟少了
每次裁剪重新渲染的程序,非常靈活 & 加載速度快
C. 記憶體開銷小
默認的 Bitmap 格式是 RGB_565 格式,而 Picasso 默認的是 ARGB_8888 格式,這個記憶體開銷要小一
半,
Android關于圖片記憶體計算,共有四種,分別是:
ALPHA_8:每個像素占用1byte記憶體
ARGB_4444:每個像素占用2byte記憶體
ARGB_8888:每個像素占用4byte記憶體(默認,色彩最細膩=顯示質量最高=占用的記憶體也最大)
RGB_565:每個像素占用2byte記憶體(8bit = 1byte)
舉例說明:一個32位的PNG=ARGB_8888=1204x1024,那么占用空間是:1024x1024x(32/8) =
4,194,304kb=4M左右
在決議圖片的時候,為了避免oom和節省記憶體,最好使用ARGB_4444模式(節省一半的記憶體空間)
1.3.2缺點
1.使用方法復雜
Glide功能強大,但代碼量大、流轉復雜,在較深掌握的情況下才推薦使用,免得出了問題難以下
手解決,
1.4 Glide與其他第三方庫的比較

1.5 Glide用法
1.5.1首先添加依賴
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
1.5.2 Glide的一個完整的請求至少需要三個引數
代碼如下:
ImageView imageView = findViewById(R.id.imageView);
Glide.with(context)
.load(url)
.into(imageView);
? with(Context context) - 需要背景關系,這里還可以使用 Activity、FragmentActivity、
android.support.v4.app.Fragment、android.app.Fragment 的物件,將 Activity/Fragment 物件作為
引數的好處是,圖片的加載會和 Activity/Fragment 的生命周期保持一致,例如:onPaused 時暫停加
載,onResume 時又會自動重新加載,所以在傳參的時候建議使用 Activity/Fragment 物件,而不是
Context.
? load(String url) - 這里我們所使用的一個字串形式的網路圖片的 URL,后面會講解 load() 的更多使用方式.
? .into(imageView);into(ImageView imageView) - 你需要顯示圖片的目標 ImageView.
1.5.3 占位圖設定
? 偶爾出現圖片加載慢或者加載不出來的情況是難以避免的,所以為了 UI 能好看一些,我們會使用占
位圖,Glide 也為我們提供這種方法 placeHolder() 和 error()
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Glide.with(context)
.load(url)
.placeholder(R.drawable.place_image)圖片加載出來前,顯示的圖片
.error(R.drawable.error_image)//圖片加載失敗后,顯示的圖片
.into(imageView);
**注:這里需要注意一點,**placeholder() 和 error() 的引數都是只支持 int 和 Drawable 型別的參
數,這種設計應該是考慮到使用本地圖片比網路圖片更加合適做占位圖,
1.5.4 縮略圖
Glide.with(context)
.load(url)
.thumbnail(0.2f)
.into(imageView);
呼叫 thumbnail() 方法,引數是 float 型別,作為其倍數大小,例如,你傳入 0.2f 作為引數,Glide
將會顯示原始圖片的20%的大小,使用 thumbnail() 方法來設定是簡單粗暴的,但是如果縮略圖需要通過網路加載相同的全尺寸圖片,就不會很快的顯示了,所以 Glide 提供了另一種防止去加載縮略圖,先看
代碼
private void loadImageThumbnailRequest(){
// setup Glide request without the into() method
DrawableRequestBuilder<String> thumbnailRequest = Glide.with( context ).load( url );
// pass the request as a a parameter to the thumbnail request
Glide.with( context )
.load( url )
.thumbnail( thumbnailRequest )
.into( imageView );
}
與第一種方式不同的是,這里的第一個縮略圖請求是完全獨立于第二個原始請求的,該縮略圖可以是不同的資源圖片,同時也可以對縮略圖做不同的轉換,等等…
1.5.5 影片開關
影片效果可以讓圖片加載變得更加的平滑,crossFade() 方法強制開啟 Glide 默認的圖片淡出淡入影片,當前版本3.7.0是默認開啟的,crossFade() 還有一個多載方法 crossFade(int duration),可以控制影片的持續時間,單位ms,影片默認的持續時間是300ms,既然可以添加影片,那肯定就可以設定沒有任何淡出淡入效果,呼叫 dontAnimate()
Glide.with(context)
.load(url)
.crossFade()//或者使用 dontAnimate() 關閉影片
.placeholder(R.drawable.place_image)
.error(R.drawable.error_image)
.into(imageView);
1.5.6 圖片大小與裁剪
在專案開發程序中,指定圖片顯示大小長長可能用到,畢竟從服務器獲取的圖片不一定都是符合設計
圖的標準的,我們在這里就可以使用 override(width,height) 方法,在圖片顯示到 ImageView 之前,
重新改變圖片大小,
Glide.with(context)
.load(url)
.override(width,height)//這里的單位是px
.into(imageView);
在設定圖片到 ImageView 的時候,為了避免圖片被擠壓失真,ImageView 本身提供了 ScaleType 屬性,這個屬性可以控制圖片顯示時的方式,具體的屬性使用還是去搜索吧!Glide 也提供了兩個類似的方法 CenterCrop() 和 FitCenter(),CenterCrop() 方法是將圖片按比例縮放到足矣填充 ImageView 的尺寸,但是圖片可能會顯示不完整;而 FitCenter() 則是圖片縮放到小于等于 ImageView 的尺寸,這樣圖片是顯示完整了,但是 ImageView 就可能不會填滿了,
1.5.7 圖片的快取處理
為了更快的加載圖片,我們肯定希望可以直接拿到圖片,而不是進行網路請求,所以我們需要快取,Glide 通過使用默認的記憶體和磁盤快取來避免不必要的網路請求,之后我們再詳細的去看它的實作
1.記憶體快取
記憶體快取是 Glide 默認幫我們做了的,除非你不需要,可以呼叫 skipMemoryCache(true) 告訴 Glide跳過記憶體快取,這樣 Glide 就不會把這張圖片放到記憶體快取中,該方法只影響記憶體快取,(不要問呼叫skipMemoryCache(false)的問題,Glide 是默認將圖片放入記憶體快取中的)
2.磁盤快取
磁盤快取也是默認開啟的,當然也是可以關閉的,不過關閉的方式略微有點不一樣,
Glide.with(context)
.load(url)
.skipMemoryCache(true)
.diskCacheStrategy( DiskCacheStrategy.NONE )
.into(imageView);
2.1自定義磁盤快取行為
使用 DiskCacheStrategy 可以為 Glide 配置磁盤快取行為,Glide 的磁盤快取比較復雜,這也是在圖片加載可以比 Picasso 的原因(之一),Picasso 只快取了全尺寸的圖片,而 Glide 的不同之處在于,Glide 不僅快取了全尺寸的圖,還會根據 ImageView 大小所生成的圖也會快取起來,比如,請求一個 800x600 的圖加載到一個 400x300 的 ImageView 中,Glide默認會將這原圖還有加載到 ImageView 中的 400x300 的圖也會快取起來,
DiskCacheStrategy 的列舉意義:
DiskCacheStrategy.NONE 什么都不快取
DiskCacheStrategy.SOURCE 只快取全尺寸圖
DiskCacheStrategy.RESULT 只快取最終的加載圖
DiskCacheStrategy.ALL 快取所有版本圖(默認行為)
Glide.with(context)
.load(url)
.diskCacheStrategy( DiskCacheStrategy.SOURCE )
.into(imageView);
1.5.8 圖片優先級
同一時間加載多個圖片,App 將難以避免這種情況,如果這個時候我們希望用戶的體驗更好,往往會
選擇先加載對于用戶更加重要的圖片,Glide 可以呼叫 .priority() 方法配合 Priority 列舉來設定圖片加
載的優先級,
//設定 HIGH 優先級
Glide.with( context )
.load( highPriorityImageUrl )
.priority (Priority.HIGH )
.into( imageView );
//設定 LOW 優先級
Glide.with( context )
.load( lowPriorityImageUrl )
.priority( Priority.LOW )
.into( imageView );
Priority.LOW
Priority.NORMAL
Priority.HIGH
Priority.IMMEDIAT
//這里有一點需要注意,優先級并不是完全嚴格遵守的,Glide 將會用他們作為一個準則,盡可能的處理這 些請求,但是不能保證所有的圖片都會按照所有要求的順序加載,
1.5.9 顯示 Gif 和 Video
顯示 GIf 對于 Glide 來說一個比較特別的功能(至少 Picasso 暫時還不行)而且使用起來非常簡單
Glide.with( context )
.load( gifUrl )
.placeholder( R.drawable.default )
.error( R.drawable.error )
.into( imageView );
這段代碼還有點問題,如果加載的不是一張 gif 圖的話,是沒有辦法顯示的,
Glide.with( context )
.load( gifUrl )
.asGif()
.error( R.drawable.error )
.into( imageView );
做以上修改,如果圖片型別不是 Gif 圖的話就會當作 load 失敗來處理,因此 error() 會被回呼,即使這個url的圖片是好的,也是不會顯示的,當然,如果你想顯示 Gif 但只是向現實靜態的圖片你就可以這么做
Glide.with( context )
.load( gifUrl )
.asBitmap()
.error( R.drawable.error )
.into( imageView );
僅僅是顯示 Gif 的第一幀影像,這樣就可以保證圖片的正常顯示了,
還有一個神奇的功能,Glide 還能顯示視頻!But…只能夠顯示手機本地的視頻,要是向現實網路上的視頻的話,還是另尋他法吧!
Glide.with( context )
.load( Uri.fromFile( new File( filePath ) ) )
.into( imageView );
二、Glide原始碼分析
2.1 Glide.with().load().into() 流程分析

2.2 相關類原始碼分析
2.2.1 基本用法
with()
創建一個加載圖片的實體
接收Context,Activity或Fragment引數,也
可以為ApplicationContext
與生命周期有關
load()
用于指定待加載的圖片資源
Glide.with( context )
.load( gifUrl )
.asBitmap()
.error( R.drawable.error )
.into( imageView );
String filePath = “/storrage/emulated/0/Pictures/video.mp4”;
Glide.with( context )
.load( Uri.fromFile( new File( filePath ) ) )
.into( imageView );包括網路圖片,本地圖片,uri等
多個方法多載
into()
希望圖片顯示在哪個ImageView上
placeholder()
占位圖
diskCacheStrategy()
硬碟快取策略
error()
例外占位圖
asGif() || asBitmap
只允許gif或靜態圖
override()
指定圖片大小
2.2.2 原始碼分析
Gilde.with(this).load(url).into(imageView)…
略.
2.2.3 Glide****的異步加載機制

采用三個執行緒池:
加載源檔案的執行緒池,包括網路加載
加載硬碟快取的執行緒池
影片執行緒池
2.2.4 執行緒切換策略-Handler**

Glide使用andriod提供的Handler 和 Looper 來滿足執行緒間的通信,
Handler先進先出原則,Looper類用來管理特定執行緒內物件之間的訊息交換(MessageExchange),
1)Looper: 一個執行緒可以產生一個Looper物件,由它來管理此執行緒里的MessageQueue(訊息佇列), 2)Handler: 你可以構造Handler物件來與Looper溝通,以便push新訊息到MessageQueue里;或者接收 Looper從Message Queue取出)所送來的訊息,
3)Message Queue(訊息佇列):用來存放執行緒放入的訊息,
4)執行緒:UIthread 通常就是main thread,而Android啟動程式時會替它建立一個MessageQueue,
2.3 快取機制
2.3.1 快取機制總覽圖

2.3.2 快取機制流程圖

2.3.3 Glide****快取功能相關用法
設定記憶體快取開關:
skipMemoryCache(true)
設定磁盤快取模式:
diskCacheStrategy(DiskCacheStrategy.NONE)
可以設定4種模式:
- DiskCacheStrategy.NONE:表示不快取任何內容,
- DiskCacheStrategy.SOURCE:表示只快取原始圖片,
- DiskCacheStrategy.RESULT:表示只快取轉換過后的圖片(默認選項),
- DiskCacheStrategy.ALL :表示既快取原始圖片,也快取轉換過后的圖片,
2.4 Glide加載圖片主要類
首先我們想下一個圖片框架,應該包含哪幾個模塊:

對外介面:封裝該框架的功能介面,一般為單例模式,
獲取圖片Request:為每個圖片加載創建一個Request,用來準備資料、請求圖片資源,
異步處理:不管從網路還是從本地讀取圖片都是耗時操作,需要在子執行緒中完成,
網路連接 :網路獲取圖片的必備模塊,
解碼 :獲得圖片流后要解碼得到圖片物件,
上面幾部分是圖片框架所必備的模塊,Glide也不例外,接下來看看Glide各模塊對應的主要類:

Glide:Glide除了是介面封裝類,還負責創建全域使用的工具和組件,
GenericRequest:為每個圖片加載創建一個Request,初始化這張圖片的轉碼器、圖片變換器、圖片展示器target等,當然這個程序實在GenericRequestBuilder的實作類里完成的,
Engine:異步處理總調度器,EnginJob負責執行緒管理,EngineRunnable是一個異步處理執行緒,DecodeJob是真正執行緒里獲取和處理圖片的地方,
HttpUrlFetcher :獲取網路流,使用的是HttpURLConnection,
Decoder :讀取網路流后,解碼得到Bitmap或者gifResource,因為加載圖片型別不同,這快分支較多,學習Glide初級階段,這塊可以先不再詳細分析,
接下來我們進入主題,快取的代碼在上面流程圖里的什么位置?記憶體快取的操作應該是在異步處理之前,磁盤快取是耗時操作應該是在異步處理中完成,
2.5 Glide記憶體快取原始碼分析
記憶體快取的 讀存都在Engine類中完成,
2.5.1 Glide記憶體快取的特點
記憶體快取使用弱參考和LruCache結合完成的,弱參考來快取的是正在使用中的圖片,圖片封裝類
Resources內部有個計數器判斷是該圖片否正在使用,
2.5.2 Glide記憶體快取的流程
- 讀:是先從lruCache取,取不到再從弱參考中取;
- 存:記憶體快取取不到,從網路拉取回來先放在弱參考里,渲染圖片,圖片物件Resources使用計數加一;
- 渲染完圖片,圖片物件Resources使用計數減一,如果計數為0,圖片快取從弱參考中洗掉,放入lruCache快取,
具體看原始碼:
Engine在加載流程的中的入口方法是load方法:
public class Engine implements EngineJobListener,
MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
...
public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,
DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,
Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {
Util.assertMainThread();
long startTime = LogTime.getLogTime();
final String id = fetcher.getId();
//生成快取的key
EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),
loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),
transcoder, loadProvider.getSourceEncoder());
//從LruCache獲取快取圖片
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from cache", startTime, key);
}
return null;
}
//從弱參考獲取圖片
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from active resources", startTime, key);
}
return null;
}
EngineJob current = jobs.get(key);
if (current != null) {
current.addCallback(cb);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Added to existing load", startTime, key);
}
return new LoadStatus(cb, current);
}
EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);
DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation,
transcoder, diskCacheProvider, diskCacheStrategy, priority);
EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
jobs.put(key, engineJob);
engineJob.addCallback(cb);
engineJob.start(runnable);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Started new load", startTime, key);
}
return new LoadStatus(cb, engineJob);
}
...
}
上面是從記憶體快取中讀取圖片的主流程:
- 生成快取的key,
- 從LruCache獲取快取圖片,
- LruCache沒取到,從弱參考獲取圖片,
- 記憶體快取取不到,進入異步處理,
我們具體看取圖片的兩個方法loadFromCache()和loadFromActiveResources(),loadFromCache使用的就是LruCache演算法,loadFromActiveResources使用的就是弱參考,我們來看一下它們的原始碼:
public class Engine implements EngineJobListener,
MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
private final MemoryCache cache;
private final Map<Key, WeakReference<EngineResource<?>>> activeResources;
...
private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {
if (!isMemoryCacheable) {
return null;
}
EngineResource<?> cached = getEngineResourceFromCache(key);
if (cached != null) {
cached.acquire();
activeResources.put(key, new ResourceWeakReference(key, cached, getReferenceQueue()));
}
return cached;
}
private EngineResource<?> getEngineResourceFromCache(Key key) {
Resource<?> cached = cache.remove(key);
final EngineResource result;
if (cached == null) {
result = null;
} else if (cached instanceof EngineResource) {
result = (EngineResource) cached;
} else {
result = new EngineResource(cached, true /*isCacheable*/);
}
return result;
}
private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {
if (!isMemoryCacheable) {
return null;
}
EngineResource<?> active = null;
WeakReference<EngineResource<?>> activeRef = activeResources.get(key);
if (activeRef != null) {
active = activeRef.get();
if (active != null) {
active.acquire();
} else {
activeResources.remove(key);
}
}
return active;
}
...
}
loadFromCache()方法:
- 首先就判斷isMemoryCacheable是不是false,如果是false的話就直接回傳null,這就是skipMemoryCache()方法設定的是否記憶體快取已被禁用,
- 然后呼叫getEngineResourceFromCache()方法來獲取快取,在這個方法中,會從中獲取圖片快取LruResourceCache,LruResourceCache其實使用的就是LruCache演算法實作的快取,
- 當我們從LruResourceCache中獲取到快取圖片之后會將它從快取中移除,將快取圖片存盤到activeResources當中,activeResources就是弱參考的HashMap,用來快取正在使用中的圖片,
loadFromActiveResources()方法:
- 就是從activeResources這個activeResources當中取值的,使用activeResources來快取正在使用中的圖片,用來保護正在使用中的圖片不會被LruCache演算法回收掉,
這樣我們把從記憶體讀取圖片快取的流程搞清了,那是什么時候存盤的呢,想想什么時候合適?是不是應該在異步處理獲取到圖片后,再快取到記憶體?
public class Engine implements EngineJobListener,
MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
...
@Override
public void onEngineJobComplete(Key key, EngineResource<?> resource) {
Util.assertMainThread();
// A null resource indicates that the load failed, usually due to an exception.
if (resource != null) {
resource.setResourceListener(key, this);
if (resource.isCacheable()) {
//將正在加載的圖片放到弱參考快取
activeResources.put(key, new ResourceWeakReference(key, resource, getReferenceQueue()));
}
}
jobs.remove(key);
}
...
}
在onEngineJobComplete()方法里將正在加載的圖片放到弱參考快取,那什么時候放在LruCache里呢?當然是在使用完,那什么時候使用完呢?
那我們來看EngineResource這個類是怎么標記自己是否在被使用的,EngineResource是用一個acquired變數用來記錄圖片被參考的次數,呼叫acquire()方法會讓變數加1,呼叫release()方法會讓變數減1,代碼如下所示:
class EngineResource<Z> implements Resource<Z> {
private int acquired;
...
void acquire() {
if (isRecycled) {
throw new IllegalStateException("Cannot acquire a recycled resource");
}
if (!Looper.getMainLooper().equals(Looper.myLooper())) {
throw new IllegalThreadStateException("Must call acquire on the main thread");
}
++acquired;
}
void release() {
if (acquired <= 0) {
throw new IllegalStateException("Cannot release a recycled or not yet acquired resource");
}
if (!Looper.getMainLooper().equals(Looper.myLooper())) {
throw new IllegalThreadStateException("Must call release on the main thread");
}
if (--acquired == 0) {
listener.onResourceReleased(key, this);
}
}
}
可以看出當參考計數acquired變數為0,就是沒有在使用了,然后呼叫了listener.onResourceReleased(key, this);
這個listener就是Engine物件,我們來看下它的onResourceReleased()方法:
public class Engine implements EngineJobListener,
MemoryCache.ResourceRemovedListener,
EngineResource.ResourceListener {
private final MemoryCache cache;
private final Map<Key, WeakReference<EngineResource<?>>> activeResources;
...
@Override
public void onResourceReleased(Key cacheKey, EngineResource resource) {
Util.assertMainThread();
activeResources.remove(cacheKey);
if (resource.isCacheable()) {
cache.put(cacheKey, resource);
} else {
resourceRecycler.recycle(resource);
}
}
...
}
做了三件事:
- 從弱參考洗掉圖片快取
- 是否支持快取,快取到LruCache快取
- 不支持快取直接呼叫垃圾回收,回收圖片
到這里記憶體快取的讀和存的流程就介紹完了,根據原始碼回頭看看我們之前列的Glide記憶體快取流程,就清晰很多了,
2.6 Glide磁盤快取原始碼分析
2.6.1 Glide磁盤快取流程
先列下主流程,再具體看代碼
- 讀:先找處理后(result)的圖片,沒有的話再找原圖,
- 存:先存原圖,再存處理后的圖,
注意一點:diskCacheStrategy設定的的快取模式即影響讀取,也影響存盤,
具體看原始碼:
原始碼入口位置是在EngineRunnable的run()方法,run()方法中呼叫到decode()方法,decode()方法的原始碼:
private Resource<?> decode() throws Exception {
if (isDecodingFromCache()) {
//從磁盤快取讀取圖片
return decodeFromCache();
} else {
//從原始位置讀取圖片
return decodeFromSource();
}
}
來看一下decodeFromCache()方法的原始碼,如下所示:
private Resource<?> decodeFromCache() throws Exception {
Resource<?> result = null;
try {
//先嘗試讀取處理后的快取圖
result = decodeJob.decodeResultFromCache();
} catch (Exception e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Exception decoding result from cache: " + e);
}
}
if (result == null) {
//再嘗試讀取原圖的快取圖
result = decodeJob.decodeSourceFromCache();
}
return result;
}
處理后的快取圖和原圖快取圖對應的是DiskCacheStrategy.RESULT和DiskCacheStrategy.SOURCE這兩個快取模式,
到DecodeJob具體看下這兩個讀取磁盤快取的方法,decodeResultFromCache()和decodeSourceFromCache():
public Resource<Z> decodeResultFromCache() throws Exception {
if (!diskCacheStrategy.cacheResult()) {
return null;
}
long startTime = LogTime.getLogTime();
Resource<T> transformed = loadFromCache(resultKey);
startTime = LogTime.getLogTime();
Resource<Z> result = transcode(transformed);
return result;
}
public Resource<Z> decodeSourceFromCache() throws Exception {
if (!diskCacheStrategy.cacheSource()) {
return null;
}
long startTime = LogTime.getLogTime();
Resource<T> decoded = loadFromCache(resultKey.getOriginalKey());
return transformEncodeAndTranscode(decoded);
}
這里兩個方法都先判斷了是否是對應的快取模式,不是則讀取失敗,這里我們不關注transform 和transcode的相關功能,只分析快取功能,兩個快取方法都呼叫到了loadFromCache()方法,只是傳入的key不同,一個是處理后圖片的key,一個是原始圖片的key,
繼續看loadFromCache()方法的原始碼:
private Resource<T> loadFromCache(Key key) throws IOException {
File cacheFile = diskCacheProvider.getDiskCache().get(key);
if (cacheFile == null) {
return null;
}
Resource<T> result = null;
try {
result = loadProvider.getCacheDecoder().decode(cacheFile, width, height);
} finally {
if (result == null) {
diskCacheProvider.getDiskCache().delete(key);
}
}
return result;
}
原始碼中可以看到我們是從diskCacheProvider.getDiskCache()中讀取的快取,diskCacheProvider.getDiskCache()獲得的是DiskLruCache工具類的實體,然后從DiskLruCache獲取快取,之后的decode不是本篇的關注點,先不分析,
到這里我們把從磁盤快取讀取快取的流程講完了,那什么時候存入的呢?肯定是在從原始位置獲取圖片后,我們回到decodeFromSource()方法,一步步看進去:
public Resource<Z> decodeFromSource() throws Exception {
Resource<T> decoded = decodeSource();
return transformEncodeAndTranscode(decoded);
}
decodeSource()顧名思義是用來決議原圖片的,而transformEncodeAndTranscode()則是用來對圖片進行轉換和轉碼的,我們先來看decodeSource()方法:
private Resource<T> decodeSource() throws Exception {
Resource<T> decoded = null;
try {
long startTime = LogTime.getLogTime();
//從網路獲取圖片
final A data = fetcher.loadData(priority);
if (isCancelled) {
return null;
}
decoded = decodeFromSourceData(data);
} finally {
fetcher.cleanup();
}
return decoded;
}
private Resource<T> decodeFromSourceData(A data) throws IOException {
final Resource<T> decoded;
//判斷設定了是否快取原圖
if (diskCacheStrategy.cacheSource()) {
decoded = cacheAndDecodeSourceData(data);
} else {
long startTime = LogTime.getLogTime();
decoded = loadProvider.getSourceDecoder().decode(data, width, height);
}
return decoded;
}
private Resource<T> cacheAndDecodeSourceData(A data) throws IOException {
long startTime = LogTime.getLogTime();
SourceWriter<A> writer = new SourceWriter<A>(loadProvider.getSourceEncoder(), data);
diskCacheProvider.getDiskCache().put(resultKey.getOriginalKey(), writer);
startTime = LogTime.getLogTime();
Resource<T> result = loadFromCache(resultKey.getOriginalKey());
return result;
}
decodeSource()方法中獲取圖片后,呼叫到decodeFromSourceData()方法,然后判斷是否快取原圖,是的話就呼叫到cacheAndDecodeSourceData(A data)方法,看進去,還是呼叫了 diskCacheProvider.getDiskCache()獲取DiskLruCache工具類的實體,然后呼叫put方法快取了原圖,
到此我們快取了原圖,處理后的圖片是什么時候快取的?肯定是在圖片處理之后,在transformEncodeAndTranscode()方法中:
private Resource<Z> transformEncodeAndTranscode(Resource<T> decoded) {
long startTime = LogTime.getLogTime();
Resource<T> transformed = transform(decoded);
writeTransformedToCache(transformed);
startTime = LogTime.getLogTime();
Resource<Z> result = transcode(transformed);
return result;
}
private void writeTransformedToCache(Resource<T> transformed) {
if (transformed == null || !diskCacheStrategy.cacheResult()) {
return;
}
long startTime = LogTime.getLogTime();
SourceWriter<Resource<T>> writer = new SourceWriter<Resource<T>>(loadProvider.getEncoder(), transformed);
diskCacheProvider.getDiskCache().put(resultKey, writer);
}
transformEncodeAndTranscode中先對圖片進行了轉換,然后呼叫writeTransformedToCache(transformed);判斷是否快取處理后的圖片,是就對處理后的圖片進行了快取,呼叫的同樣是DiskLruCache實體的put()方法,不過這里用的快取Key是resultKey,
2.7 快取機制時序圖

寫在最后
本篇文章是參考了幾篇簡書上的文章,以及自己的部分總結而成對Glide的分析,有需要的同學可以進行相關的查閱
參考文章:https://www.jianshu.com/p/17644406396b
? https://www.jianshu.com/p/7ce7b02988a4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/23874.html
標籤:其他
上一篇:想了解游戲美術外包的一般流程
