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

Android 中使用 SVG 圖片格式

編輯:關於 Android 程式設計

SVG 自適應屏幕、體積小,優點不少。本文說明如何在 Android 項目裡使用 SVG。

SVG:Scalable Vector Graphics,可縮放矢量圖形。
IRI:Internationalized Resource Identifiers,國際化資源標識符。

一、Android Studio 2.0 及以上:Vector Asset

先準備一張 SVG 圖片,新建項目後嘗試顯示它。

路徑:File -> New -> Vector Asset -> Local SVG file

導入時可以勾選重置圖片大小與左右布局適配,讓生成的 VectorDrawable 更貼合使用場景。AS 會自動在 drawable 目錄下生成對應的 xml 文件。

使用方式和普通圖片資源完全一樣:

<ImageView
    android:contentDescription="@null"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:src="@drawable/homer_simpson" />

顯示效果:

二、Android Studio 2.0 以下:在線轉換

舊版本沒有 Vector Asset 功能,可以改用在線工具。

網址:https://inloop.github.io/svg2android/

上傳 SVG 圖片後即可生成代碼:

轉換時同樣建議勾選刪除空組與添加變換,能顯著精簡輸出結果。

生成後下載代碼,或者在 drawable 文件夾中新建 .xml 文件把代碼粘貼進去。使用方式與 AS 自動生成的完全一致,直接引用即可。

三、體積對比

實測均為 500x500 的圖片:

· AS 自動生成的 SVG:約 20KB
· 在線生成的 SVG:約 29KB
· PNG(放大的系統圖片):約 732KB

差距非常明顯,SVG 在體積上的優勢不言而喻。對於圖片資源眾多的大型 App,全面擁抱 SVG 的吸引力相當大。

OK, Enjoy It.

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