我要画一条虚线。我现在用这个来画实线:
LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );
我需要这样的东西,但不是实心的,而是虚线的。我想避免在透明布局和固体布局之间交替制作数百个布局。
我不知道为什么,但投票的答案不适合我。我这样写,效果很好。
定义一个自定义视图:
public class XDashedLineView extends View {
private Paint mPaint;
private Path mPath;
private int vWidth;
private int vHeight;
public XDashedLineView(Context context) {
super(context);
init();
}
public XDashedLineView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public XDashedLineView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.parseColor("#3F577C"));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setPathEffect(new DashPathEffect(new float[] {10,10}, 0));
mPath = new Path();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
this.vWidth = getMeasuredWidth();
this.vHeight = getMeasuredHeight();
mPath.moveTo(0, this.vHeight / 2);
mPath.quadTo(this.vWidth / 2, this.vHeight / 2, this.vWidth, this.vHeight / 2);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(mPath, mPaint);
}
}
然后你可以在你的xml中使用它:
<com.YOUR_PACKAGE_NAME.XDashedLineView
android:layout_width="690dp"
android:layout_height="1dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="620dp"/>
唯一对我有用的方法,我认为这是最简单的方法,就是使用Path和一个paint对象,就像这样:
Paint paintDash = new Paint();
paintDash.setARGB(255, 0, 0, 0);
paintDash.setStyle(Paint.Style.STROKE);
paintDash.setPathEffect(new DashPathEffect(new float[]{10f,10f}, 0));
paintDash.setStrokeWidth(2);
Path pathDashLine = new Path();
然后onDraw():(重要调用重置,如果你改变这些点之间的onDraw调用,导致路径保存所有的移动)
pathDashLine.reset();
pathDashLine.moveTo(porigenX, porigenY);
pathDashLine.lineTo(cursorX,cursorY);
c.drawPath(pathDashLine, paintDash);