Android平台的Drawable代表可以繪製在螢幕上的資源,可以使用getDrawable(int)從資源檔中擷取Drawable 資源,或者在XML資源檔中採用 @drawable來引用一個drawable資源。
Drawable資源可以分為 Bitmap ,Nine-Patch, Layer List, State List, Level List, Transition ,Insert ,Clip ,Scale 和Shape 多種類型。
本例GradientDrawable 介紹了 Sharp Drawable資源的用法:
Shape資源可以定義一個矩形 (rectangle),橢圓(oval),線段(line),環形(ring)等簡單二維圖形,對應每種二維圖形,還可以通過Corners定義邊角形狀,Gradient 漸層填充模式, padding ,size, solid (顏色), stroke(繪製輪廓的模式) 等屬性。
本例的layout資源檔為shape_drawable_1.xml 定義如下:
<ScrollView xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”@drawable/white”>
<LinearLayout
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
>
<ImageView
android:layout_width=”match_parent”
android:layout_height=”50dip”
android:src=”@drawable/shape_1″ />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:src=”@drawable/line” />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”50dip”
android:src=”@drawable/shape_2″ />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:src=”@drawable/line” />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”50dip”
android:src=”@drawable/shape_3″ />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:src=”@drawable/line” />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”50dip”
android:src=”@drawable/shape_4″ />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:src=”@drawable/line” />
<ImageView
android:layout_width=”match_parent”
android:layout_height=”50dip”
android:src=”@drawable/shape_5″ />
</LinearLayout>
</ScrollView>
原例在模擬器上背景色為黑色,造成有幾個Shape無法看到(這幾個shape也是採用黑色來繪製的,因此需對這個資源做些修改,定義一個drawable white顏色資源:
<drawable name=”white”>#ffffffff</drawable>
然後將 layout的背景定義為白色, 這個資源定義了五個Shape Drawable 資源,每個資源之間有一個橫線@drawable/line隔開。
這裡我們只看一下Shape5的定義: 這對應於本例的Title :GradientDrawable
<shape xmlns:android=”http://schemas.android.com/apk/res/android”
android:shape=”rectangle”>
<gradient android:startColor=”#FFFF0000″
android:endColor=”#80FF00FF”
android:angle=”270″/>
<padding android:left=”7dp” android:top=”7dp”
android:right=”7dp” android:bottom=”7dp” />
<corners android:radius=”8dp” />
</shape>
這個Shape的基本類似為rectangle, 定義的漸層的角度為270度,(必須為90的整數倍) ,為圓角矩形(corners定義)。
作者:mapdigit