Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Glide 圖片緩存配置終極指南:從框架選型到 GlideModule 全局定製

編輯:關於 Android 程式設計

Glide 之所以成為眾多 Android 項目的默認圖片加載方案,除了 API 順手,更關鍵的是它那套可深度定製的緩存體系。本文先談談在眾多加載庫中為何選 Glide,再逐層拆解 Glide 的鍵值生成、失效策略、GlideModule 配置、內存與磁盤緩存、自定義 Target 以及轉換器。

零、為什麼首推 Glide

我用過的加載庫不少:Afinal 的 AfinalBitmap、Xutils 的 BitmapUtils、老牌 UniversalImageLoader、Square 的 Picasso、Google 官方推薦的 Glide,以及 Facebook 的 Fresco。逐一體驗之後,選擇思路大致如下。

Afinal 與 Xutils 的作者早已停止維護;這類「快速開發框架」功能應有盡有,小項目確實省事,但耦合度偏高,一旦停止維護而新問題不斷湧現,就會很被動。

在 Glide 與 Fresco 出現之前,最流行的是 UniversalImageLoader 和 Picasso。我最初選了 Picasso,因為 UIL 的配置項太多、沒有實踐過根本不知道怎麼配,最後往往全用默認值,還不如直接上 Picasso。用了將近一年沒出大問題——但也可能只是當時項目太簡單、週期太短,加上用 Eclipse 開發看不到內存與 CPU 的即時監控。

換到 Android Studio 之後,性能監控一目了然,這才找到過去頁面卡頓的元兇:Picasso 加載稍大一點的圖片就極度耗內存,而 ListView 或頂部輪播往往一屏就有好幾張圖,於是只要圖片多一點,頁面就異常卡頓(從前我還把責任推給測試機性能差)。

後來我把 Picasso、Glide、UniversalImageLoader、Fresco 四個庫放在一起做對比測試,項目包括內存佔用、大圖加載、小圖加載、本地圖與網絡圖,並結合各自特色功能:

  • 內存表現:Glide、UIL、Fresco 都很優秀;Picasso 差距明顯,圖片稍大,內存消耗就是別人的好幾倍。
  • 大圖(2MB 以上):Fresco 和 Picasso 一樣直接什麼都不顯示。項目需要大圖預覽功能,這一點就出局了。
  • 綜合:UIL 與 Glide 成績都很好,最終選 Glide 的理由有三個——用法幾乎是「另一個 Picasso」,遷移改動最小;由 Google 維護,可信度更高;支持 GIF 與短視頻,後續需求用得上。

Glide 的緩存機制也確實聰明:默認使用 RGB_565 而非 ARGB_8888,能省下可觀空間;能與 Activity/Fragment/Application 的生命週期聯動,更合理地管理請求。唯一要留意的是方法數比 UIL 多出一千多個,對 64K 問題敏感的同學需要關注。

Fresco 我原本期待很高:支持 WebP(同質量下比 JPG 更省空間)、支持漸進式 JPEG、可定製各類屬性、支持多圖請求與圖片復用、支持手勢縮放旋轉。但實際使用下來,不少功能仍待完善,穩定性也有起伏。

最後提醒一個工程習慣:不要直接把任何加載庫裸用在業務裡,至少先做一層簡單封裝。舉個例子,後期圖片量大可能需要單獨配置一台機器存放圖片,主機地址要可配置——如果到處硬編碼 URL,這時就得加班了。

一、Glide 3.x 的重要新特性

1. GIF 動態圖加載

 Glide.with(context).load(...).asBitmap() //顯示gif靜態圖片
 Glide.with(context).load(...).asGif() //顯示gif動態圖片 

2. 本地視頻取幀

Glide 可以把視頻解碼成一張圖片:

 Glide.with(context).load(“視頻路徑“) 

實測只能解析手機本地的 mp4 視頻,放在 raw 文件裡的 mp4 無法解析。

3. 縮略圖支持

 //加載yourView1/10尺寸的縮略圖,然後加載全圖
 Glide.with(yourFragment).load(yourUrl).thumbnail(0.1f).into(yourView) 

4. 生命週期集成

把 Activity/Fragment 作為 with() 的參數有個實打實的好處:圖片加載會與宿主生命週期保持同步——onStop 時自動暫停請求,onStart 時重新啟動,GIF 動畫也會在 onStop 時停止,避免在後台白白耗電。

5. 轉碼

toBytes() 與 transcode() 允許在後台完成取圖、解碼與格式轉換,例如把一張圖裁成 250×250 後上傳:

 Glide.with(context)
 .load(“/user/profile/photo/path”)
 .asBitmap()
 .toBytes()
 .centerCrop()
 .into(new SimpleTarget<byte[]>(250, 250) {
 @Override public void onResourceReady(byte[] data, GlideAnimation anim) {
 // Post your bytes to a background thread and upload them here.
 } }); 

6. 動畫

3.x 加入了 cross fade 與 View 屬性動畫支持:

 (.animate(ViewPropertyAnimation.Animator)) 

7. 網絡層可替換

可以在 OkHttp、Volley 與 Glide 自帶的 HttpUrlConnection 之間自由選擇,只需在 gradle 中添加依賴並註冊對應的 ModelLoaderFactory。

二、緩存的鍵值與失效機制

1. 緩存鍵值由三部分組成

主要影響 DiskCacheStrategy.RESULT。Glide 的 key 由以下內容混合生成:

  • DataFetcher.getId() 返回的字符串。一般實現會直接返回數據模型的 toString(),URL/File 則返回相應路徑。
  • 圖片尺寸,由 override(width, height) 或 Target 的 getSize() 決定。
  • 一個可選的簽名(Signature)。

這些信息經過散列算法生成一個唯一且安全的文件名,圖片就以該名義緩存在磁盤上。

2. 讓緩存失效

由於 key 是散列出來的,很難手工指定要刪哪個緩存文件。實務上的做法是「改變標識符」。

當內容(URL、文件路徑)發生變化時,用 signature() 往 key 裡追加一份附加數據即可:

 Glide.with(yourFragment)
 .load(yourFileDataModel)
 .signature(new StringSignature(yourVersionMetadata))
 .into(yourImageView);
 Glide.with(fragment)
 .load(mediaStoreUri)
 .signature(new MediaStoreSignature(mimeType, dateModified, orientation))
 .into(view); 

多媒體存儲用 MediaStoreSignature(把修改時間、mimeType 等信息納入 key),文件與 URL 則用 StringSignature。

自定義簽名只需實現 Key 接口:

 public class IntegerVersionSignature implements Key { private int currentVersion; public IntegerVersionSignature(int currentVersion) { this.currentVersion = currentVersion; } @Override public boolean equals(Object o) { if (o instanceof IntegerVersionSignature) { IntegerVersionSignature other = (IntegerVersionSignature) o; return currentVersion = other.currentVersion; } return false; } @Override public int hashCode() { return currentVersion; } @Override public void updateDiskCacheKey(MessageDigest md) { messageDigest.update(ByteBuffer.allocate(Integer.SIZE) .putInt(signature).array()); } } 

完全不緩存則用 diskCacheStrategy(DiskCacheStrategy.NONE)。

三、配置 GlideModule

GlideModule 是 Glide 的統一配置入口,用來調整全局選項並註冊自定義組件。

第一步,實現接口:

 public class MyGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { // Apply options to the builder here. } @Override public void registerComponents(Context context, Glide glide) { // register ModelLoaders here. } } 

第二步,在混淆文件中保留類名:

 -keepnames class * com.mypackage.MyGlideModule 

第三步,在 AndroidManifest.xml 中添加 meta-data,讓 Glide 找得到它:

 <meta-data android:name="com.bumptech.glide.samples.flickr.FlickrGlideModule" android:value="GlideModule" /> 

四、Library 項目中的 GlideModule

一個 Library 項目可以定義一個或多個 GlideModule。只要 Module 被寫進 Library 的 manifest,依賴該 Library 的 App 就會自動加載。但若 manifest 合併不正確,就必須在 App 中手動補上。

五、GlideModule 衝突怎麼辦

Glide 允許一個 App 中存在多個 GlideModule,但不保證調用順序。當多個依賴工程各自帶了同名的 Module,就可能衝突。

如果衝突無法避免,建議在 App 中自己定義一個 Module 統一處理,並在 manifest 合併時用 tools:node="remove" 排除衝突項:

 <meta-data android:name=”com.mypackage.MyGlideModule” tools:node=”remove”/> 

六、用 GlideBuilder 配置全局選項

所有全局配置都在 applyOptions() 的 GlideBuilder 參數上完成。

1. 磁盤緩存 DiskCache

磁盤緩存在後台線程進行,透過 DiskCache.Factory 決定位置與大小。

Glide 默認用 InternalCacheDiskCacheFactory 在 App 內部緩存目錄下建立一個最大 250MB 的緩存文件夾。使用內部目錄而非 SD 卡,意味著其他 App 無法訪問這些圖片。

調整容量:

 builder.setDiskCache(new InternalCacheDiskCacheFactory(context, yourSizeInBytes)); 

自定義路徑(例如放到外存):

 builder
 .setDiskCache(new DiskCache.Factory() {
 @Override public DiskCache build() {
 // Careful: the external cache directory doesn't enforce permissions
 File cacheLocation = new File(context.getExternalCacheDir(), "cache_dir_name");
 cacheLocation.mkdirs();
 return DiskLruCacheWrapper.get(cacheLocation, yourSizeInBytes);
 } }); 

要完全禁用磁盤緩存,傳入 DiskCacheAdapter 即可。

2. 內存緩存與 Bitmap Pool

默認大小由 MemorySizeCalculator 依屏幕尺寸推算,可以先讀出默認值再決定怎麼調:

 MemorySizeCalculator calculator = new MemorySizeCalculator(context);
 int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
 int defaultBitmapPoolSize = calculator.getBitmapPoolSize(); 

想整體提高內存緩存等級:

 Glide.get(context).setMemoryCategory(MemoryCategory.HIGH); 

單獨設置內存緩存容量(LruResourceCache):

 builder.setMemoryCache(new LruResourceCache(yourSizeInBytes)); 

設置 Bitmap 池容量(LruBitmapPool 是默認實現):

 builder.setBitmapPool(new LruBitmapPool(sizeInBytes)); 

內存緩存的目的在於減少 I/O、提高命中效率;Bitmap 池的目的則是複用對象、降低 GC 壓力,兩者互補而非重複。

3. 解碼格式

Glide 默認用 RGB_565,內存佔用約為 ARGB_8888 的一半。若對畫質有更高要求,可全局切換:

 builder.setDecodeFormat(DecodeFormat.ALWAYS_ARGB_8888); 

七、自定義顯示控件 Target

1. SimpleTarget:不經過 View 直接拿結果

如果你只是想拿到一張 Bitmap 做別的事——顯示一條 notification、上傳頭像——用 SimpleTarget 最合適,它把 Target 的樣板代碼都封好了,你只需實現 onResourceReady。

 int myWidth = 512;
 int myHeight = 384;
 Glide.with(yourApplicationContext))
 .load(youUrl)
 .asBitmap()
 .into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
 @Override public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
 // Do something with bitmap here.
 } }; 

幾點說明:

  • 加載到 View 時,宿主 Activity/Fragment 失去焦點或銷毀,Glide 會自動停止加載,避免浪費。
  • 如果希望加載不受組件生命週期影響,Glide.with() 裡傳的應是 Application Context,而不是 Activity 或 Fragment。
  • 耗時較長的操作可能造成內存洩露,建議改用靜態內部類而非非靜態內部類。

2. ViewTarget:接管顯示環節

當你想加載圖片到 View,同時要改寫 Glide 的默認行為(自定義尺寸計算、自定義顯示動畫),就繼承 ViewTarget:

 Glide.with(yourFragment)
 .load(yourUrl)
 .into(new ViewTarget<YourViewClass, GlideDrawable>(yourViewObject) {
 @Override public void onResourceReady(GlideDrawable resource, GlideAnimation anim) {
 YourViewClass myView = this.view;
 // Set your resource on myView and/or start your animation here.
 } }); 

加載靜態圖或 GIF 時,在 load 之後補上 asBitmap()/asGif(),會替換掉 ViewTarget 泛型中的 GlideDrawable;也可以實現 LifecycleListener 給 target 掛回調。

3. 覆蓋默認設置

只想沿用 Glide 默認行為、僅做少量擴充,可以直接繼承兩個現成子類:

  • GlideDrawableImageViewTarget:默認實現,配合 asGif() 加載動態圖。
  • BitmapImageViewTarget:配合 asBitmap() 加載靜態圖。
 Glide.with(yourFragment)
 .load(yourUrl)
 .asBitmap()
 .into(new BitmapImageViewTarget(yourImageView)) {
 @Override public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
 super.onResourceReady(bitmap, anim);
 Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
 @Override public void onGenerated(Palette palette) {
 // Here's your generated palette
 } });
 } }); 

關鍵是記得呼叫 super.onResourceReady(),否則 Glide 的默認顯示流程會被中斷。

八、按目標尺寸下載圖片

ModelLoader 能把「加載該圖片的 View 尺寸」交給你,讓你決定要下載多大的圖。選對尺寸既能省流量又能省存儲,還能降低 OOM 風險。

Google 在 2014 年 I/O 大會的 iosched 項目裡就是這麼做的,原始碼中的說明文件值得一讀:https://github.com/google/iosched/blob/master/doc/IMAGES.md

通過 http/https 下載時,繼承 BaseGlideUrlLoader 即可:

 public interface MyDataModel { public String buildUrl(int width, int height); } public class MyUrlLoader extends BaseGlideUrlLoader<MyDataModel> { @Override protected String getUrl(MyDataModel model, int width, int height) { // Construct the url for the correct size here. return model.buildUrl(width, height); } } 

使用自定義 ModelLoader:

 Glide.with(yourFragment)
 .using(new MyUrlLoader())
 .load(yourModel)
 .into(yourView); 

若不想每次都寫 using(new MyUrlLoader()),實現一個 ModelLoaderFactory 並在 GlideModule 中註冊:

 public class MyGlideModule implements GlideModule { ... @Override public void registerComponents(Context context, Glide glide) { glide.register(MyDataModel.class, InputStream.class, new MyUrlLoader.Factory()); } } 

之後就能省略 using():

 Glide.with(yourFragment)
 .load(yourModel)
 .into(yourView); 

九、集成庫

Glide 提供了一些體積很小、可選的集成庫,目前涵蓋 Volley 與 OkHttp。集成庫配合 ModelLoader 體系,讓網絡層能與項目中其他部分保持統一。

集成分兩步:加對依賴、寫對 GlideModule。

Volley:

 dependencies { compile 'com.github.bumptech.glide:volley-integration:1.2.2'
 compile 'com.mcxiaoke.volley:library:1.0.5' } 
 <meta-data android:name="com.bumptech.glide.integration.volley.VolleyGlideModule" android:value="GlideModule" /> 
 -keep class com.bumptech.glide.integration.volley.VolleyGlideModule
 #or
 -keep public class * implements com.bumptech.glide.module.GlideModule 

OkHttp:

 dependencies { compile 'com.github.bumptech.glide:okhttp-integration:1.2.2'
 compile 'com.squareup.okhttp:okhttp:2.0.0' } 
 <meta-data android:name="com.bumptech.glide.integration.okhttp.OkHttpGlideModule" android:value="GlideModule" /> 
 -keep class com.bumptech.glide.integration.okhttp.OkHttpGlideModule
 #or
 -keep public class * implements com.bumptech.glide.module.GlideModule 

十、在後台線程加載與緩存

除了 Glide.with(fragment).load(url).into(view),Glide 還提供了三個適合後台使用的入口:

 downloadOnly(int width, int height)
 downloadOnly(Y target)// Y extends Target<File>
 into(int width, int height) 

1. downloadOnly:只要文件,不要顯示

在後台線程下載:

 FutureTarget<File> future = Glide.with(applicationContext)
 .load(yourUrl)
 .downloadOnly(500, 500);
 File cacheFile = future.get(); 

future.get() 返回後,圖片的二進制數據已進入磁盤緩存。要注意 downloadOnly 只保證字節數據在磁盤上有效,並不保證解碼後的 Bitmap。

下載完要顯示時:

 Glide.with(yourFragment)
 .load(yourUrl)
 .diskCacheStrategy(DiskCacheStrategy.ALL)
 .into(yourView); 

用 DiskCacheStrategy.ALL 或 SOURCE 才能確保程序去讀緩存文件,而不是重新發請求。

2. into():後台取得 Bitmap

 Bitmap myBitmap = Glide.with(applicationContext)
 .load(yourUrl)
 .asBitmap()
 .centerCrop()
 .into(500, 500)
 .get() 

注意:這行只能在異步線程調用。如果在主線程呼叫 .get(),會直接阻塞 UI。

十一、轉換器 Transformation

1. 默認轉換器

Glide 內建 fitCenter 與 centerCrop;想要圓形、圓角等更多形態,可以參考 https://github.com/wasabeef/glide-transformations

 Glide.with(yourFragment)
 .load(yourUrl)
 .fitCenter()
 .into(yourView);
 Glide.with(yourFragment)
 .load(yourUrl)
 .centerCrop()
 .into(yourView);
 // For Bitmaps:
 Glide.with(yourFragment)
 .load(yourUrl)
 .asBitmap()
 .centerCrop()
 .into(yourView);
 // For gifs:
 Glide.with(yourFragment)
 .load(yourUrl)
 .asGif()
 .fitCenter()
 .into(yourView); 

轉換甚至能發生在類型轉換的過程中:

 Glide.with(yourFragment)
 .load(yourUrl)
 .asBitmap()
 .toBytes()
 .centerCrop()
 .into(new SimpleTarget<byte[]>(...) { ... }); 

2. 自定義轉換器

第一步,繼承 BitmapTransformation:

 private static class MyTransformation extends BitmapTransformation { public MyTransformation(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { Bitmap myTransformedBitmap = ... // apply some transformation here. return myTransformedBitmap; } @Override public String getId() { // Return some id that uniquely identifies your transformation. return "com.example.myapp.MyTransformation"; } } 

第二步,用 transform() 取代 fitCenter()/centerCrop():

 Glide.with(yourFragment)
 .load(yourUrl)
 .transform(new MyTransformation(context))
 .into(yourView);
 // For Bitmaps:
 Glide.with(yourFragment)
 .load(yourUrl)
 .asBitmap()
 .transform(new MyTransformation(context))
 .into(yourView);
 // For Gifs:
 Glide.with(yourFragment)
 .load(yourUrl)
 .asGif()
 .transform(new MyTransformation(context))
 .into(yourView); 

getId() 千萬別省,它是緩存 key 的一部分;返回值不唯一會導致不同轉換共用同一份緩存,出現「圖形錯亂」的怪 bug。

3. 轉換尺寸怎麼定

不指定時,Glide 會依 View 的實際尺寸自動推算,通常已經夠聰明。若要強制指定,用 override(int, int) 覆蓋寬高。

4. Bitmap 復用

為減少 GC,可以透過 BitmapPool 歸還與取用 Bitmap。典型流程是:從 pool 取一個 Bitmap → 回設給 Canvas → 用 Matrix/Paint 或 Shader 在上面作畫。

有一條硬性規則:不要手動 recycle 轉換後的 Bitmap,也不要把它放回 BitmapPool,交給 Glide 處理即可:

 protected Bitmap transform(BitmapPool bitmapPool, Bitmap original, int width, int height) { Bitmap result = bitmapPool.get(width, height, Bitmap.Config.ARGB_8888); // If no matching Bitmap is in the pool, get will return null, so we should //allocate. if (result == null) { // Use ARGB_8888 since we're going to add alpha to the image. result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } // Create a Canvas backed by the result Bitmap. Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setAlpha(128); // Draw the original Bitmap onto the result Bitmap with a transformation. canvas.drawBitmap(original, 0, 0, paint); // Since we've replaced our original Bitmap, we return our new Bitmap here. Glide will // will take care of returning our original Bitmap to the BitmapPool for us. return result; }

實踐清單

把上面的內容濃縮成一份可執行的檢查表:

  1. 項目啟動時自定義一個 GlideModule,統一管理磁盤緩存路徑與容量、內存緩存等級、解碼格式。
  2. 對服務端圖片做多尺寸支持,用 ModelLoader 按 View 尺寸取圖,而不是全-size 下載再縮放。
  3. 內容可能變化的圖(頭像、商品圖)一律帶 signature(),避免緩存髒數據。
  4. 對加載庫做一層薄封裝,把前綴地址、占位圖、錯誤圖、默認轉換器收攏到一處。
  5. 涉及 64K 方法數上限的項目,提前開啟 ProGuard/R8 並保留 GlideModule。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved