從 Android 5.0 開始,Drawable 新增了可縮放向量圖形 (SVG) 的用法,
優點是可以任意縮放圖片卻不會失真。
只要在 XML 檔裡定義即可使用,下面是
官方所提供的範例(改成紅色的):
<!-- res/drawable/heart.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- intrinsic size of the drawable -->
android:height="256dp"
android:width="256dp"
<!-- size of the virtual canvas -->
android:viewportWidth="32"
android:viewportHeight="32">
<!-- draw a path -->
<path android:fillcolor="#ff0000"
android:pathdata="M20.5,9.5
c-1.955,0,-3.83,1.268,-4.5,3
c-0.67,-1.732,-2.547,-3,-4.5,-3
C8.957,9.5,7,11.432,7,14
c0,3.53,3.793,6.257,9,11.5
c5.207,-5.242,9,-7.97,9,-11.5
C25,11.432,23.043,9.5,20.5,9.5z">
</path>
</vector>
|
圖1. Heart |
Vector 詳細有哪些屬性可以設定,可以參考新增的
VectorDrawables 類別,
pathdata 中語法和 SVG 的語法一樣 M 指的是 moveto,C 是
curveto,z 是 closepath,
大寫為絕對位置,小寫為相對位置,更多 pathdata 的用法可以直接參考
SVG 的文件。
畫了個西瓜來當練習:
<!-- res/drawable/heart.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="256dp"
android:viewportheight="32"
android:viewportwidth="32"
android:width="256dp" >
<!-- watermelon-->
<path android:fillcolor="#ff0000"
android:strokecolor="#086D08"
android:strokewidth="1"
android:pathdata="M3,3
C3,13 23,13 23,3" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M5,4
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M8,6
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M12,8
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M14,5
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M18,6
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
<!-- seed-->
<path android:fillcolor="#000000"
android:strokecolor="#000000"
android:strokewidth="0.5"
android:pathdata="M20,4
a0.2,0.2 0 1,0 0.4,0
a0.2,0.2 0 1,0 -0.4,0" />
|
圖2. Watermelon |