Android绘制虚线的两种方式
1.自定义view
看到网上很多人说用drawLine绘制,但是其实根本就没有效果,真正效果的是drawPath这个方法,话不多说直接上代码
public class DotView extends View { private Paint mLinePaint; private Paint mPaint; private Path mPath; private Context context; public DotView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(dip2px(context,0.5f)); mPaint.setColor(getResources().getColor(R.color.colorPrimary)); mPaint.setStyle(Paint.Style.STROKE); DashPathEffect dashPathEffect1 = new DashPathEffect(new float[]{dip2px(context,3), dip2px(context,3)}, 0); mPaint.setPathEffect(dashPathEffect1); mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mLinePaint.setStrokeWidth(1); mLinePaint.setStyle(Paint.Style.STROKE); mLinePaint.setColor(getResources().getColor(R.color.colorAccent)); mPath = new Path(); this.context = context; } public DotView(Context context) { this(context, null); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPath.reset(); mPath.moveTo(100, 100); mPath.lineTo(100, 200); canvas.drawPath(mPath, mPaint); } public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } } 注解:DashPathEffect参数含义new float[]{dip2px(context,3), dip2px(context,4)} :3:代表实现长度 4:代表两个实现间距离 最后面的0:代表开始的偏移量 2.使用shape dashWidth:虚线宽度,0表示实线 ;dashGap:虚线间隔
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line"> <size android:height="1dp" /> <stroke android:dashGap="6dp" android:dashWidth="9dp" android:width="6dp" android:color="#848C99" /> </shape>