ShapeDrawable:用于传入一个形状shape用来控制管理该形状在屏幕上的显示状态(位置,圆角,渐变,颜色等)如未传入形状则默认为矩形
- 1.在XML文件中定义shapeDrawable,res/drawable/下新建一个XML文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false">//是否作为LevelListDrawable(等级列表图片,每个图片都有一个android:maxlevel大于或等于setlevel的值时就会被现实,如充电的动态图)使用,一般设置为false
<!--传入管理的形状取值为["rectangle"(默认形状)矩形 | "oval"椭圆形 | "line"直线 | "ring"环形],在XML中只能传入这三种形状-->
<!--corners 圆角,只有当shape是rectangle时才有效-->
<corners
android:bottomLeftRadius="5dp"//左上角的圆角半径
android:bottomRightRadius="5dp"//右上角的圆角半径
android:topLeftRadius="5dp"//左下角的圆角半径
android:topRightRadius="5dp"//右下角的圆角半径
android:radius="5dp"/>//所有角的圆角半径,可被分别制定的圆角半径覆盖
<!--gradient指定shape的渐变色-->
<gradient
android:type="radial"//渐变类型linear(线性渐变),"radial"(径向渐变),"sweep"(扫描性渐变)
android:angle="90"//渐变的角度水平为0,垂直为90,必须是45的整数倍数,默认为0
android:centerX="0f"//相对于渐变中心的X方向的位置取值范围(0f,1f)
android:centerY="0f"//相对于渐变中心的Y方向的位置取值范围(0f,1f)
android:startColor="#FF00FF00"//渐变起始颜色(颜色模式为ARGB)
android:centerColor="#FF0000FF"//渐变中间过渡颜色
android:endColor="#FFFF0000"//渐变结束颜色
android:gradientRadius=""/>//渐变半径,当渐变类型为radial(径向渐变)时才有效
<!--padding 设置视图内容与形状边界的内间距-->
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp"/>
<!--size形状shape的宽高-->
<size
android:height="300dp"
android:width="200dp"/>
<!--solid形状shape的单色填充色-->
<solid
android:color="#FF00ff00"/>
<!--storke 形状shape的描边-->
<stroke
android:color=""//描边颜色
android:width=""//描边宽度
android:dashGap=""//虚线描边的各小线段之间的距离,只有与dashwidth合用才有效
android:dashWidth=""/>//虚线描边的宽度,只有与dashwidth合用才有效
</shape>
- 2.在代码中实例化XML中的shapeDrawable
Drawable drawable = getResources().getDrawable(R.drawable.cricle_drawable);//实例化drawable
textView.setBackground(drawable);//将Drawable作为View的background
- 3.在Java中直接定义ShapeDrawable
OvalShape circle = new OvalShape();//新建一个圆形(可以是ArcShape(弧形),OValShape(圆形),RectShape,RoundRectShape(圆角矩形))
float mDensity = getContext().getResources().getDisplayMetrics().density;//获得显示屏幕的分辨率
circle.resize(50 * mDensity, 50 * mDensity);//更改圆形的大小
ShapeDrawable shapeDrawable = new ShapeDrawable(circle);//新建一个ShapeDrawable,将圆形传入进去
shapeDrawable.draw(canvas)//将shapeDrawable在画布上画出来