Android實現畫虛線的控制元件
在Android的UI開發中,有時為了介面美觀而需要虛線。我自己實現一個虛線控制元件。
package com.custom;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
/**
* 畫虛線元件
* @author linweidong
* @Date 2010-09-15
*/
public class DashedLine extends View {
private final String namespace = "http://com.smartmap.driverbook";
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();
path.moveTo(0, 10);
path.lineTo(480,10);
PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);
paint.setPathEffect(effects);
canvas.drawPath(path, paint);
}
在layout資料夾下的xml引用這個控制元件
<com.custom.DashedLine
android:id="@+id/dashedLine"
android:layout_width="wrap_content"
android:layout_height="20px"
/>