很多时候,画虚线都是使用美工切图(一个实点,一个虚点),然后使用Bitmap的repeat属性
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/repeat_bg"
android:tileMode="repeat" />
下面我们来画一条虚线,首先定义一个 dashedline类,继承于View,重写Ondraw()方法
public class DashedLine extends View {
private final String namespace = "http://www.android-study.com/";
private float startX;
private float startY;
private float endX;
private float endY;
private Rect mRect;
public DashedLine(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);//空心
paint.setColor(Color.DKGRAY);
Path path = new Path();
//通过moveto,lineto的x,y坐标确定虚线实横,纵,还是倾斜
path.moveTo(0, 10);//Set the beginning of the next contour to the point (x,y)
path.lineTo(480, 10);//Add a line from the last point to the specified point (x,y).
//DashPathEffect 可以使用DashPathEffect来创建一个虚线的轮廓(短横线/小圆点),而不是使用实线
//float[] { 5, 5, 5, 5 }值控制虚线间距,密度
PathEffect effects = new DashPathEffect(new float[] { 5, 5, 5, 5 }, 1);
paint.setPathEffect(effects);
canvas.drawPath(path, paint);
}
}
定义完View,就可以在XML中使用了