shape绘制虚线
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DashLineView">
<attr name="line_space" format="dimension"/>
<attr name="blank_space" format="dimension"/>
<attr name="line_color" format="color"/>
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
</resources>
public class DashLine extends View {
private Context context;
private Paint paint = new Paint();
private int orientation = 0;
private int lineColor;
private int lineSpace;
private int blankSpace;
private Path path = new Path();
public DashLineView(Context context) {
this(context, null);
}
public DashLineView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DashLineView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
initAttrs(attrs);
init();
}
private void initAttrs(AttributeSet attrs) {
if (attrs == null) {
return;
}
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashLineView);
orientation = typedArray.getInteger(R.styleable.DashLineView_orientation, 0);
lineColor = typedArray.getInteger(R.styleable.DashLineView_line_color, Color.WHITE);
lineSpace = typedArray.getDimensionPixelOffset(R.styleable.DashLineView_line_space, dp2px(5));
blankSpace = typedArray.getDimensionPixelOffset(R.styleable.DashLineView_blank_space, dp2px(5));
}
private void init() {
paint.setColor(lineColor);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[]{lineSpace, blankSpace}, 0));
post(new Runnable() {
@Override
public void run() {
if (orientation == 0) {
paint.setStrokeWidth(getMeasuredHeight());
} else {
paint.setStrokeWidth(getMeasuredWidth());
}
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.moveTo(0, 0);
if (orientation == 0) {
path.lineTo(getWidth(), 0);
} else {
path.lineTo(0, getHeight());
}
canvas.drawPath(path, paint);
}
public int dp2px(float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics());
}
}
<包名.DashLine
android:layout_width="match_parent"
android:layout_height="1dp"
app:line_space="5dp"
app:blank_space="5dp"
app:line_color="@color/black"
app:orientation="horizontal"/>