在Android软件的编写过程中,可以通过使用shape可以进行一些简单的UI开发。
在shape属性中,支持的形状类型包括:
rectangle:矩形
oval:椭圆形
line:线条
ring:环形
shape中,包含的基本属性有:corners、solid、gradient、stroke、padding、size等。下面分别说是这几个属性的含义。
1. corners属性
corners属性的作用是用来定义圆角,它包含以下几个属性:
android:radius="dimension" //全部的圆角半径
android:topLeftRadius="dimension" //左上角的圆角半径
android:topRightRadius="dimension" //右上角的圆角半径
android:bottomLeftRadius="dimension" //左下角的圆角半径
android:bottomRightRadius="dimension" //右下角的圆角半径
需要注意的是radius属性与其他属性是互斥的,不能同时使用。
2. solid属性
solid属性用于填充颜色,它只包含一个属性:
android:color="color"
3. gradient属性
gradient属性用于实现渐变色,它包含以下几个属性:
android:type=["linear" | "radial" | "sweep"] //共有3中渐变类型,线性渐变(默认)/放射渐变/扫描式渐变
android:angle="integer" //渐变角度,必须为45的倍数,0为从左到右,90为从上到下
android:centerX="float" //渐变中心X的相当位置,范围为0~1
android:centerY="float" //渐变中心Y的相当位置,范围为0~1
android:startColor="color" //渐变开始点的颜色
android:centerColor="color" //渐变中间点的颜色,在开始与结束点之间
android:endColor="color" //渐变结束点的颜色
android:gradientRadius="float" //渐变的半径,只有当渐变类型为radial时才能使用
android:useLevel=["true" | "false"] //使用LevelListDrawable时就要设置为true。设为false时才有渐变效果
4. stroke属性
stroke属性用于设置边界属性,可以设置边界的宽度、颜色、虚实等。它包含的属性如下:
android:width="dimension" //描边的宽度
android:color="color" //描边的颜色
// 以下两个属性设置虚线
android:dashWidth="dimension" //虚线的宽度,值为0时是实线
android:dashGap="dimension" //虚线的间隔
5. padding属性
padding属性用于定义内部边距。它包含的属性如下:
android:left="dimension"
android:top="dimension"
android:right="dimension"
android:bottom="dimension"
6. size属性
size属性用于定义图形的大小。它包含的属性如下:
android:width="dimension"
android:height="dimension"
这个属性一般使用较少,因为在控件中我们就能够直接定义图形的大小,而不需要再在这里重新定义。
7. 使用示例
首先先在drawable文件夹中新建一个xml文件,这边命名为test_shape.xml,代码如下:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="15dip"/>
<stroke
android:color="#0000FF"
android:width="2dip"/>
<solid
android:color="#FFFFFF"/>
<padding
android:top="5dip"
android:bottom="5dip"
android:left="15dip"
android:right="15dip"/>
</shape>
这边定义的是一个矩形形状,四个圆角半径为15dip,变现颜色为蓝色,线宽为2dip,填充为白色,上下内部边距为5dip,左右内部边距为15dip。
然后将该该形状应用到具体的控件上,例如使用到按键上,则使用:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/test_shape" //通过background使用shape
android:textSize="30sp"
android:text="开始使用"/>
这样就能够应用我们编写的shape了。
8. 动态修改shape
在代码中,如果需要修改通过shape定义的background,则使用GradientDrawable类实现具体实现方式举例如下:
//对上述的Button的shape进行修改
Button button=;//获取Button
GradientDrawable drawable=(GradientDrawable) button.getBackground();
/*设置边框宽度和颜色*/
drawable.setStroke(5, getResources().getColor(R.color.color_1));
/*设置背景颜色*/
drawable.setColor(getResources().getColor(R.color.color_2));
/*设置圆角*/
drawable.setCornerRadius();