shape是android drawable资源中的一个重要的角色,drawable资源覆盖面广,它不仅代表图片,它可以是一个颜色,一个形状,因为shape其简单实用,下面我们来看一下shape形状的分类:
rectangle:代表矩形,它是shape默认的形状类型,即如果我们不在shape的android:shape
属性指定其类型时,默认是矩形
oval:椭圆,用它可以画椭圆,圆
line:水平线,在使用该形状的时候,我们得给它指定stroke元素指定其宽度,不然在使用该形状的时候会报空指针异常
ring:环形
<Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/shape_s" android:text="椭圆形" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/button2" android:layout_below="@+id/button" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" android:background="@drawable/shape_z" android:text="长方圆角形"/> <Button android:id="@+id/button4" android:layout_below="@id/button2" android:text="描边" android:layout_marginTop="30dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/line"/> <Button android:layout_below="@id/button4" android:text="环形" android:layout_marginTop="30dp" android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="250dp" android:background="@drawable/ring"/>
设置椭圆形
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <corners android:radius="8dp"/> <gradient android:centerColor="#ff0000" android:endColor="#00ff00" android:startColor="#0000ff"/> </shape>
设置长方圆角形
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:radius="8dp"/> 设置渐变颜色,可随意更改 <gradient android:centerColor="#ff0000" android:endColor="#00ff00" android:startColor="#0000ff"/> </shape>
设置描边
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:width="60dp" android:height="30dp"/> <!-- 设置描边 --> <stroke android:width="2dp" android:color="#f00" android:dashWidth="5dp" android:dashGap="5dp"> </stroke> <corners android:radius="15dp" android:topRightRadius="0dp" android:bottomRightRadius="0dp" /></shape>
设置环形
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="ring" android:innerRadius="100dp" android:thickness="10dp" android:useLevel="false"> <stroke android:width="10dp" android:color="#f00" /> </shape>
效果图