1. 程式人生 > >Android使用shape繪製各種形狀

Android使用shape繪製各種形狀

在開發中經常會用到shape標籤來定義控制元件的背景,好處是減少apk的佔記憶體大小,shape標籤總共有四個圖形選項,分別是rectangle(矩形),oval(橢圓),line(橫線)和ring(圓環)。

res下新建一個Drawable resource file:

矩形效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#ff5900"/>
</shape>

圓角矩形效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#ff5900"/>
    <corners android:radius="20dp"/>
</shape>

注;radius表示四個邊角都設定。也可以只設置一個邊角的弧度效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#ff5900"/>
    <corners android:topLeftRadius="40dp"/>
</shape>

圓形效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#3700ff"/>
    <size android:height="50dp" android:width="50dp"/>
</shape>

環形效果:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="100dp"
    android:shape="ring"
    android:thickness="2dp"
    android:useLevel="false" >
    <!-- 設定固定填充色 -->
    <solid android:color="#f00" />
    <size android:height="44dp"/>
</shape>

虛線條:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
    <stroke android:width="2dp" android:color="@color/colorAccent" android:dashWidth="20dp" android:dashGap="10dp"/>
</shape>

屬性:

width:線的粗細

dashWidth:小線條的長度

dashgap:線條的間隙

 

線漸變效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#24abff"
        android:centerColor="@color/white"
        android:endColor="#ff00d0"
        android:angle="0"
        android:type="linear"/>
</shape>

屬性:

startColor:開始顏色

centerColor:中間顏色

endColor:結束顏色

angle:漸變的角度(必須是45的倍數)

type:漸變型別:(linear表示線性漸變;sweep表示雷達漸變)

雷達漸變效果:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#25ba0b"
        android:endColor="#ff0000"
        android:angle="0"
        android:type="sweep"/>
</shape>