很多時候,畫虛線都是使用美工切圖(一個實點,一個虛點),然後使用Bitmap的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);}@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubsuper.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中使用了