Android animation 30天上手 — Day20 VectorDrawable 向量圖

Evan Chen
Evan Android Note
Published in
6 min readNov 14, 2018

接下來我們要來介紹有趣的了,VectorDrawable向量圖與VectorDrawable Animation 向量圖動畫。將分為5篇來介紹:

VectorDrawable 向量圖
VectorDrawable Animation Morphs
VectorDrawable Animation Path
VectorDrawable Animation 範例 play-pause
VectorDrawable Animation 匯入動畫

SVG是指可縮放向量圖形(Scalable Vector Graphics,SVG)用XML描述二維向量圖形的圖形格式。

而VectorDrawable 即是Android實現SVG向量圖的方式。VectorDrawable可以讓你用xml的方式來建立圖形資源。

Android 預設有豐富的Vector資源,在res/drawable右鍵,New -> Vector asset

自訂VectorDrawable

在Gradle defaultConfig 加上 vectorDrawables.useSupportLibrary = true

android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}

從最簡單的畫矩形開始

res/drawable 新增rect.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="120dp"
android:height="120dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:name="iconPath"
android:fillColor="#274fe1"
android:pathData="M8,5 V21 H16 V5 z" />
</vector>

我們先來看vector 裡面的屬性

  • width 圖片寬度
  • height 圖片高度
  • viewportWidth 在這個vector繪制裡所用的單位寬度
  • viewportHeight 在這個vector繪制裡所用的單位高度

path 是用來繪制圖形

  • fillColor 填充顏色
  • pathData 路徑
  • android:strokeColor 框線顏色
  • android:strokeWidth 框線寬度

pathData 路徑,使用座標搭配以下指令來繪出向量圖

M 移動畫筆到指定座標
L 畫一條直線到絕對位置(x,y)
l 畫一條直線到相對位置(x,y)
H 畫一水平線到絕對路徑x座標
h 畫一水平線到相對路徑x座標
V 畫一垂直線到絕對路徑y座標
v 畫一垂直線到相對路徑y座標
Z 關閉路徑

android:pathData=”M8,5 V19 H16 V5 z”

指令步驟如下:
(1) M 8,5 將畫筆移至座標8,5
(2) V19 畫一條垂直線至Y軸為19
(3) H16 畫一條水平線至X軸為16
(4) V5 畫一條垂直線至X軸為5
(5) z 關閉路徑

pathData的每個指令可以加上空格較容易閱讀。

再來看另一個例子

<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="120dp"
android:height="120dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:name="iconPath"
android:fillColor="#274fe1"
android:pathData="M8,5 v14 l11,-7 z" />
</vector>

(1) M8,5 畫筆移到絕對位置 8,5
(2) v14 垂直至相對位置y14
(3) l11,-7 至相對位置 11,-7
(4) z 關閉路徑

這邊要注意一下優化重繪效能,每個VectorDrawable會創建一個bitmap cache。 所以參考到相同的VectorDrawable意謂著參考相同的bitmap cache。如果這些引用不相同的大小,則每次更改大小時都將重新創建並重繪bitmap。換句話說,如果VectorDrawable用於不同的大小,每個大小建立一個VectorDrawable是比較好的選擇。

以上就是使用VectorDrawable,下一篇我們讓VectorDrawable動起來吧。

完整程式:
https://github.com/evanchen76/VectorDrawableSample

參考:https://developer.android.com/reference/android/graphics/drawable/VectorDrawable

下一篇:Day21 VectorDrawable Animation Morphs

--

--