//自定义虚线控件 可以动态改变虚线颜色 虚线间距 虚线长度 虚线高度 /** * 虚线控件 * */ public class DashLineView extends View { /** * 虚线颜色 */ private int dashColor; /** * 虚线间距 */ private float dashGap; /** * 虚线长度 */ private float dashWith; /** * 虚线高度 */ private float lineHegiht; private Paint paint; private Path path; private int widthScreen; public DashLineView(Context context) { super(context); init(context, null); } public DashLineView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public DashLineView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashLine); dashColor = typedArray.getColor(R.styleable.DashLine_dashColor, R.color.black); dashGap = typedArray.getDimension(R.styleable.DashLine_dashGap, 5); dashWith = typedArray.getDimension(R.styleable.DashLine_dashWith, 15); lineHegiht = typedArray.getDimension(R.styleable.DashLine_lineHeight, 3); typedArray.recycle(); } paint = new Paint(); path = new Path(); //widthScreen = ToolsManager.getInstance().getScreenWidth(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Paint.Style.STROKE);// 空心 paint.setColor(dashColor); paint.setStrokeWidth(lineHegiht); path.moveTo(0, 1); path.lineTo(widthScreen, 1); // DashPathEffect 可以使用DashPathEffect来创建一个虚线的轮廓(短横线/小圆点),而不是使用实线 // float[] { 5, 5, 5, 5 }值控制虚线间距,密度 PathEffect effects = new DashPathEffect(new float[] { dashWith, dashGap, dashWith, dashGap }, 1); paint.setPathEffect(effects); canvas.drawPath(path, paint); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); widthScreen = getMeasuredWidth(); } }
<declare-styleable name="DashLine"> <attr name="dashColor" format="color" /> <attr name="dashWith" format="dimension" /> <attr name="dashGap" format="dimension" /> <attr name="lineHeight" format="dimension" /> </declare-styleable>
时间: 2024-11-10 01:30:20