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

Android 專案導入 VectorDrawable:依賴配置、向量圖建立與相容寫法

編輯:關於 Android 程式設計

向量圖(VectorDrawable)的好處很直接:同一份資源檔可自由縮放而不失真,且體積遠小於多套不同解析度的 PNG,能有效縮小 APK。以下是在專案中導入的完整步驟。

1. 加入依賴與開啟相容模式

compile 'com.android.support:support-vector-drawable:25.0.1'
compile 'com.android.support:appcompat-v7:25.0.1'

接著在 module 的建置檔中告訴 Gradle 要啟用向量圖的支援庫:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

這一步是關鍵。若不開啟,即使在相容版本的 AppCompat 上使用向量圖,在低於 API 21 的裝置上也可能出現圖示顯示不出來的問題。

2. 建立向量圖資源

在 res 目錄上按右鍵,選擇 New → Vector Asset 即可建立。這個精靈提供了兩條路:一是從內建的 Material Design 圖示庫中挑選(Clip Art),二是匯入本地的 SVG 或 PSD 檔(Local file)。建立後會在 drawable 目錄下產生一個 XML 檔。

3. 在版面中使用

要讓相容模式生效,ImageView 的圖片來源必須用 app:srcCompat 而非 android:src:

<ImageView
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_android_black_24dp" />

這是另一個容易忽略的細節:使用 android:src 時,支援庫無法介入載入流程,向量圖在舊版本上就無法正常渲染。

4. 用程式碼設定背景

若需要透過程式碼動態設定背景,要用 VectorDrawableCompat 建立 Drawable:

Resources resources = context.getResources();
Theme theme = context.getTheme();
Drawable drawable = VectorDrawableCompat.create(
        resources, R.drawable.vector_drawable, theme);
view.setBackground(drawable);

直接用 ContextCompat.getDrawable() 也能取得,但 VectorDrawableCompat.create() 的顯式寫法更明確,也便於需要套用 theme 屬性的場合。

5. 使用美工提供的 SVG

Android Studio 內建 SVG 轉換工具,可以將一個 SVG 檔直接生成 VectorDrawable 資源檔,不必自己手寫路徑資料。匯入時精靈會顯示原圖與轉換後的預覽,並提示該 SVG 是否包含不支援的效果(例如某些濾鏡或漸層),能及早發現問題。

幾點實務提醒

並非所有圖形都適合向量化。向量圖擅長的是圖示、簡單插畫這類以路徑與填色構成的圖形。照片或細節極豐富的插畫仍應使用 PNG/WebP,硬轉成向量檔反而會讓 XML 龐大且渲染變慢。

用 VectorDrawableCompat 承載複雜圖形時有效能成本。在相容模式下,向量圖是在應用層完成解析與繪製的,路徑節點過多時會影響列表滾動的流暢度,建議把圖示路徑控制在合理複雜度。

支援庫版本要一致。support-vector-drawable 與 appcompat-v7 的版本號應保持相同,混用不同版本容易出現方法找不到的執行期錯誤。此外,新版專案已改用 AndroidX,對應的依賴是 androidx.vectordrawable:vectordrawable 與 appcompat,寫法則完全相同。

搭配 app:tint 可以一檔多色。同一個圖示若要呈現不同顏色,不必準備多份資源,透過 tint 在執行期染色即可,這也是向量圖在實務上最實用的特性之一。

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