我要画一条虚线。我现在用这个来画实线:
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 DashedLineView extends View
{
private float density;
private Paint paint;
private Path path;
private PathEffect effects;
public DashedLineView(Context context)
{
super(context);
init(context);
}
public DashedLineView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
public DashedLineView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(context);
}
private void init(Context context)
{
density = DisplayUtil.getDisplayDensity(context);
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(density * 4);
//set your own color
paint.setColor(context.getResources().getColor(R.color.XXX));
path = new Path();
//array is ON and OFF distances in px (4px line then 2px space)
effects = new DashPathEffect(new float[] { 4, 2, 4, 2 }, 0);
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);
paint.setPathEffect(effects);
int measuredHeight = getMeasuredHeight();
int measuredWidth = getMeasuredWidth();
if (measuredHeight <= measuredWidth)
{
// horizontal
path.moveTo(0, 0);
path.lineTo(measuredWidth, 0);
canvas.drawPath(path, paint);
}
else
{
// vertical
path.moveTo(0, 0);
path.lineTo(0, measuredHeight);
canvas.drawPath(path, paint);
}
}
}
唯一对我有用的方法,我认为这是最简单的方法,就是使用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);