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

Android 向量圖(SVG / VectorDrawable)屬性含義逐項解析

編輯:關於 Android 程式設計

Android 的向量圖,每個屬性到底在控制什麼?下面只挑重要的講。

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="200dp"
    android:viewportWidth="100"
    android:viewportHeight="100"
    android:alpha="0.2">

    <group
        android:name="group_name"
        android:pivotX="50"
        android:pivotY="50"
        android:translateX="20"
        android:translateY="30"
        android:rotation="90"
        android:scaleX="0.5"
        android:scaleY="0.3">

        <path
            android:name="path_name"
            android:pathData="m 0,0 L50,0 L100,100 L0,100 z"
            android:fillColor="@color/red"
            android:fillAlpha="1"
            android:strokeColor="#ff0000ff"
            android:strokeAlpha="0.5"
            android:strokeWidth="20"
            android:strokeLineCap="butt|round|square"
            android:strokeLineJoin="round|bevel|miter"
            android:trimPathStart="0.5"
            android:trimPathEnd="0.5"
            android:trimPathOffset="0.5" />

    </group>
</vector>

vector 標籤

  • width / height:向量圖的實際顯示尺寸,單位通常是 dp。
  • viewportWidth / viewportHeight:虛擬畫布的尺寸,路徑座標就是相對這塊畫布來計算。兩者不一定要等於 width/height,縮放關係由此決定。
  • alpha:整體透明度,0 到 1。

group 標籤

group 用來把多個 path 包在一起,套用共同的變換屬性。

  • name:這一點非常關鍵。設定 objectAnimator 時,就是靠這個名字來指定動畫要施加在哪個部分。
  • pivotX / pivotY:group 的中心點座標,取值範圍 0 到 100(相對於 viewport),旋轉與縮放時以它為基準。
  • translateX / translateY:整個 group 在 X/Y 方向的平移量。
  • rotation:以中心點為軸旋轉的角度,360 為一圈。
  • scaleX / scaleY:縮放比例,1 表示 100%,0.5 表示 50%,1.5 表示 150%。

path 標籤

  • name:同樣用於 objectAnimator 的 target 指定。
  • pathData:路徑資料本身,支援 M、L、C、Q、A、Z 等指令。
  • fillColor / fillAlpha:內部填色與填色透明度。
  • strokeColor / strokeAlpha / strokeWidth:線條顏色、透明度與寬度。
  • strokeLineCap:線端樣式,butt(平頭)、round(圓頭)、square(方頭,比 butt 多出半個線寬)。
  • strokeLineJoin:轉角樣式,miter(尖角)、round(圓角)、bevel(斜切)。
  • trimPathStart / trimPathEnd / trimPathOffset:路徑裁剪,這三個最容易搞混,下面用圖說明。

trimPath 三兄弟圖解

trimPathStart = 0.1

從路徑的 0% 起算,把 0% 到 10% 這一段去掉。


trimPathStart = 0.1,trimPathOffset = 0.5

先把路徑原點移到 50% 的位置,再以它為起點,去掉 0% 到 10% 這一段。


trimPathEnd = 0.9,trimPathOffset = 0.5

同樣先把原點移到 50% 位置,再以它為起點,去掉 90% 到 100% 這一段。

幾個實務提醒

  • viewport 與實際 width/height 不一致時,線寬也會被一併縮放,設計稿對照時要留意。
  • strokeLineCap 設為 round 或 square 時,線條視覺長度會比 butt 長,對齊計算要把它算進去。
  • trimPath 系列非常適合做「線條生長」類型的動畫,只要對 trimPathEnd 做屬性動畫即可,不必重畫路徑。
  • VectorDrawable 不支援全部的 SVG 特性(例如大部分 filter、部分渐变與文字),從設計工具匯出後仍需在 Android Studio 的 Vector Asset 預覽中確認。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved