在网上一搜索如何实现Android虚线,绝大部分都说使用shape的方式实现,然后在View节点下开启软加速 android:layerType= “software”
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<stroke
android:dashGap="3dp"
android:dashWidth="6dp"
android:width="1dp"
android:color="#63a219" />
<!-- 虚线的高度 -->
<size android:height="1dp" />
</shape>
但是我在好几款机型上运行结果虚线都显示不出来,最后只好采用 “画虚线”实现了,注释都写了,应该可以看明白
public class DashLine extends View {
//画图路径
private Path mPath;
//画笔
private Paint mPaint;
//上下文
private Context mContext;
//距离多少长度画一次虚线
private int distance = 10;
//可以使paint画出类似虚线的样子,指定虚实的排列方式
private PathEffect mPathEffect;
public DashLine(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
//初始化画笔
mPaint = new Paint();
//初始化画路径
mPath = new Path();
//DashPathEffect是PathEffect类的一个子类,可以使paint画出类似虚线的样子,并且可以任意指定虚实的排列方式
//float数组,必须是偶数长度,且>=2,指定了多少长度的实线之后再画多少长度的空白
mPathEffect = new DashPathEffect(new float[]{distance, distance, distance, distance}, 1);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.reset();
mPaint.setStyle(Paint.Style.STROKE);
//设置画笔颜色
mPaint.setColor(Color.parseColor("#DCDCE2"));
mPaint.setStrokeWidth(3);
mPath.reset();
//mPath绘制的绘制起点
//path.moveTo(0, 0);
int screenWidth = ((Activity) mContext).getWindowManager().getDefaultDisplay().getWidth();
IMLog.e("tlt [DashLine] 屏幕宽度:" + screenWidth);
//添加一条线从最后一点添加到指定的点(x,y) 如果没有调用moveTo()第一点是自动设置为(0,0)
mPath.lineTo(screenWidth, 0);
mPaint.setPathEffect(mPathEffect);
canvas.drawPath(mPath, mPaint);
}
}