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

Glide 圖片載入框架入門:安裝、常用 API 與除錯技巧

編輯:關於 Android 程式設計

簡介

Android 上的圖片載入框架已經多到「爛大街」,所以這裡不評比誰好誰壞——評比出來的結論往往都是片面的。真正該問的是:它適不適合你的需求。

起因是在泰國舉辦的 Google 開發者論壇上,Google 介紹了一個名為 Glide 的圖片載入庫,作者是 bumptech。這個庫被廣泛運用在 Google 的開源專案裡,包括 2014 年 Google I/O 大會上發布的官方 App。要特別說明的是,它並不是官方庫,第一眼感覺和 Picasso 特別像,但內部實作其實差異不小。

按照我寫部落格的慣例,先跑一次 Demo——實際看過效果,才更能理解作者的專案架構,而多看看高手的架構本身就是很好的學習。

一、跑起來再說

來到 Glide 的 GitHub 首頁,會看到相當多的內容:

Glide GitHub 專案首頁

建議用 git clone 下載原始碼,而不是直接 Download zip:

git clone https://github.com/bumptech/glide.git

把程式碼 clone 到本機後,用 Android Studio 匯入並選擇最外層的 build.gradle,成功匯入後結構如下:

Glide 專案匯入 Android Studio 後的結構

其中:library 是 Glide 的源碼;samples 是各種 demo;third_party 是 library 的一些相依性庫。

接著可以運行其中的範例,直接在 Android Studio 執行,或用下列指令:

./gradlew :samples:flickr:run
./gradlew :samples:giphy:run
./gradlew :samples:svg:run

這個 run 方法是怎麼來的呢?看 gallery 的 build.gradle 就明白了:

task run(type: Exec, dependsOn: 'installDebug') {
    description 'Installs the APK and runs the main activity: "gradlew :samples:???:run"'
    commandLine "${android.sdkDirectory}/platform-tools/adb",
            'shell', 'am', 'start',
            '-n', 'com.bumptech.glide.samples.gallery/.MainActivity'
}

原來是自己在 Gradle 裡定義了一個 Exec task,先安裝 APK 再用 adb 啟動 Activity。

另一個值得學習的地方是:它把 SDK 版本與相依套件版本統一抽到 gradle.properties,要升版只改一個檔就好。gallery 目錄的 build.gradle 大致如下:

apply plugin: 'com.android.application'

dependencies {
    compile project(':library')
    compile(project(':integration:recyclerview')) {
        transitive = false
    }
    compile "com.android.support:support-v4:${SUPPORT_V4_VERSION}"
    compile "com.android.support:recyclerview-v7:${SUPPORT_V7_VERSION}"
}

android {
    compileSdkVersion COMPILE_SDK_VERSION as int
    buildToolsVersion BUILD_TOOLS_VERSION

    defaultConfig {
        applicationId 'com.bumptech.glide.samples.gallery'
        minSdkVersion MIN_SDK_VERSION as int
        targetSdkVersion TARGET_SDK_VERSION as int
        versionCode 1
        versionName "1.0"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

那些 ${SUPPORT_V4_VERSION}、COMPILE_SDK_VERSION 變數的值,就寫在 gradle.properties 裡:

COMPILE_SDK_VERSION=22
BUILD_TOOLS_VERSION=22.0.1
TARGET_SDK_VERSION=22
MIN_SDK_VERSION=10

我覺得用這種方式管理專案參數很不錯——編譯 SDK 版本、相依版本或各種設定參數都能集中維護。

執行後,這個 demo 會列出你手機裡所有的圖片:

Glide gallery demo 執行畫面

二、安裝相依套件

Gradle(推薦)

Glide 已經發佈到 jcenter,直接在外層 build.gradle 加上相依即可:

dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:19.1.0'
}

Maven

<dependency>
    <groupId>com.github.bumptech.glide</groupId>
    <artifactId>glide</artifactId>
    <version>3.7.0</version>
</dependency>
<dependency>
    <groupId>com.google.android</groupId>
    <artifactId>support-v4</artifactId>
    <version>r7</version>
</dependency>

另外官方網站也提供已編譯好的 jar 檔可直接下載。

三、Proguard 設定(很重要)

這一步千萬不要跳過。不管你現在有沒有啟用混淆,都建議先寫上去——否則哪天要開混淆時,你得回頭逐一找出所有需要 ignore 的套件,而你的相依庫絕對不只一個。

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
    **[] $VALUES;
    public *;
}

四、常用 API

最簡單的載入

Glide.with(this).load(imgUrl).centerCrop().into(iv1);

一句話就是一個完整的圖片載入流程:with() 綁定生命週期、load() 傳入來源、centerCrop() 決定裁切策略、into() 指定目標 View。

設定預留圖與載入失敗圖

Glide.with(context)
        .load(datas.get(position))
        .placeholder(R.drawable.ic_launcher)
        .error(R.drawable.error)
        .centerCrop()
        .crossFade()
        .into(holder.iv);

載入封面圖(縮圖)

一般來說封面圖可以是真實圖片的小圖或低解析度版本:

Glide.with(this)
        .load(url)
        .thumbnail(Glide.with(this).load(thumbUrl))
        .centerCrop()
        .into(iv2);

從其他路徑載入

API 重載了很多方法,除了網路網址,也支援本地檔案、資源 ID、Uri、byte[] 等多種來源,甚至还有自訂路徑:

Glide load 方法的多種重載形式

載入到其他控制項

這個需求很常見,例如要為一個 LinearLayout 設定背景圖片。可以用官方提供的自訂 Target:

Glide.with(this)
        .load(imgUrl)
        .into(new SimpleTarget<GlideDrawable>() {
            @Override
            public void onResourceReady(GlideDrawable resource,
                                        GlideAnimation<? super GlideDrawable> glideAnimation) {
                linearLayout.setBackgroundDrawable(resource);
            }
        });

五、除錯技巧

開啟請求/回應資訊

在終端機執行:

adb shell setprop log.tag.GenericRequest DEBUG

開啟後就能在 logcat 看到相關輸出:

開啟 GenericRequest DEBUG 後的 logcat 輸出

開啟工作流程日誌

這可以讓你看到 Glide 內部是怎麼找資源的——是從記憶體、磁碟還是網路取得:

adb shell setprop log.tag.Engine VERBOSE
adb shell setprop log.tag.EngineJob VERBOSE
adb shell setprop log.tag.DecodeJob VERBOSE

開啟後會看到類似下面的資訊:

開啟 Engine 相關 VERBOSE 日誌後的輸出

接下來

基本用法就到這裡。下一篇會從源碼角度帶你看 Glide 的實作,一方面學欣賞大師怎麼架構一個專案,另一方面也能順便理解一些進階用法。

幾個使用上的提醒:with() 傳入的 context 會影響快取與生命週期綁定,在 Adapter 中建議傳 fragment.getActivity() 或直接傳 View 所在的 Fragment;crossFade() 雖然視覺柔和,但在快速滾動的列表裡可能造成殘影,需要時再開。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved