通過shape可以建立一個圖形,比如圓形、四方形,定義一個圓形如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke android:color="@color/transparent_white" android:width="20dp"/>
<solid android:color="@color/red"/>
</shape>
- stroke為邊框的相關設定,如邊框線條的顔色,這裡我設定了一個半透明的白色,邊框線條的寬度,這裡設定了20dp。
- solid為圖形的填充顔色,這裡設定為紅色。
接下來我們把這個圖形顯示到Activity上,界面使用黑色背景,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/black">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape_indicator_current"
android:layout_gravity="center"/>
</FrameLayout>
顯示效果如下:
我們定義的圓形邊框線條寬度為20dp,設定了圓的寬度為100dp,除去邊框線條的寬度,則圓的填充直徑應該是60dp(100 - 20 x 2),但從效果圖我們可以發現,填充顔色和邊框的線條有重疊的,重疊的寬度是邊框線條寬度的1半。如果我想定義兩個圓形,一個圓形隻有邊框,一個圓形隻有填充顔色,這兩個圓形可以重疊在一起,但是填充顔色不能覆寫到邊框線條,了解了這個細節之後,實作這個就很簡單了,在定義填充圖形的時候,我們把它的線條寬度設定為另一個圖形的線條寬度的兩倍即可,如下:
圖形1,隻有邊框線條:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke android:color="@color/transparent_white" android:width="20dp"/>
</shape>
這裡沒有定義填充顔色預設為完全透明。
圖形2,隻有填充顔色:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke android:color="@android:color/transparent" android:width="40dp"/>
<solid android:color="@color/red"/>
</shape>
這裡設定邊框線條顔色為完全透明,雖然透明了,但是它還是占着寬度的。
兩個圖形用到界面上顯示,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/black">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape_indicator_current"
android:layout_gravity="center"/>
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/shape_indicator_normal"
android:layout_gravity="center"/>
</FrameLayout>
效果如下:
可以看到,此時的填充色和線條就沒有發生重疊的問題了。
最後,放上一個實戰效果圖,實作引導頁的訓示器效果,如下: