Android中資源檔的Shape使用總結
在Android程式開發中,我們經常會去用到Shape這個東西去定義各種各樣的形狀,首先我們瞭解一下Shape下面有哪些標籤,都代表什麼意思:
solid:填充
android:color指定填充的顏色
gradient:漸層
android:startColor和android:endColor分別為起始和結束顏色,
android:angle是漸層角度,必須為45的整數倍。
另外漸層預設的模式為android:type="linear",即線性漸層,
可以指定漸層為放射狀漸層,android:type="radial",放射狀漸層需要指定半徑android:gradientRadius="50"。
angle值對應的位置
stroke:描邊
android:width="2dp" 描邊的寬度,android:color 描邊的顏色。
我們還可以把描邊弄成虛線的形式,設定方式為:
android:dashWidth="5dp"
android:dashGap="3dp"
其中android:dashWidth表示'-'這樣一個橫線的寬度,android:dashGap表示之間隔開的距離
corners:圓角
android:radius為角的弧度,值越大角越圓。
我們還可以把四個角設定成不同的角度,
同時設定五個屬性,則Radius屬性無效
android:Radius="20dp" 設定四個角的半徑
android:topLeftRadius="20dp" 設定左上方的半徑
android:topRightRadius="20dp" 設定右上方的半徑
android:bottomLeftRadius="20dp" 設定右下角的半徑
android:bottomRightRadius="20dp" 設定左下角的半徑
padding:間隔
可以設定上下左右四個方向的間隔
在這裡我們來看一個簡單的小例子,ShapDemo,在drawable檔案夾下面先定義兩個xml檔案:
button_bg.xml的內容如下:
-
- android:width="2dp"
- android:bottomRightRadius="5dp" android:topLeftRadius="5dp"
- android:topRightRadius="5dp"/>
- android:bottom="10dp"android:right="10dp" android:top="10dp"/>
button_pressed_bg.xml的內容如下:
-
- android:gradientRadius="50" android:startColor="#ff8c00"
- android:type="radial"/>
- android:dashGap="3dp"android:width="2dp" android:color="#dcdcdc"/>
- android:bottom="10dp"android:right="10dp" android:top="10dp"/>
這裡說明一點,在描邊裡面設定了dash參數,使得圖形的邊變成了虛線在drawable檔案夾下添加一個button.xml檔案,內容如下:
這個檔案的意思以前講過,normal(正常)情況下就顯示button_bg,被press(按下)情況下就顯示button_pressed_bg。我們再來看一下layout目錄下的activity_main.xml的內容:
- android:layout_width="match_parent" android:layout_height="match_parent"> android:layout_width="wrap_content"android:background="@drawable/button" android:text="TestShapeButton"/>
直接將background指定為drawable檔案夾下的button.xml。程式運行如下: