Android虚线的实现方法

作者: android00 发布时间: 2022-04-25 浏览: 1748 次 编辑

1. 水平虚线的实现:

在drawable下新建drawable资源 shape_dotted_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="1dp"
        android:color="#32ffffff"
        android:dashWidth="4dp"
        android:dashGap="4dp" />
    <size android:height="1dp" />
</shape>

然后再在xml布局中使用该drawable做背景即可

<View
    android:layout_width="match_parent"
    android:layout_height="1.5dp"
    android:background="@drawable/shape_dotted_line"
    android:layerType="software" />
注: android:layerType="software" 如果不加这个会显示实线
view的高度也要大一点,不然虚线显示不出来

2. 垂直虚线的实现

垂直虚线只需要把水平的旋转一下即可,不过还需要做一下特殊处理

在drawable下新建drawable资源 shape_dotted_line_vertical.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-300dp"
        android:right="-300dp">
        <rotate
            android:drawable="@drawable/shape_dotted_line"
            android:fromDegrees="90" />
    </item>
</layer-list>

然后再xml布局中使用

<View
    android:id="@+id/dotted_view"
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="@drawable/shape_dotted_line_vertical"
    android:layerType="software" />
注: 如果直接旋转的话,在设置给view的背景后,发现虚线只有一小段。因为他其实是把水平的直接旋转过来的,你宽度设置的还是原来水平的,宽度设置的小的就会出现一小段的情况
通过item的 left 和 right 属性来设置左右偏移,水平的线就可以画出600dp来,然后再旋转成垂直的,这样就可以自由设置view的宽度了

3. 通过canvas绘制

使用path来做 这样可以支持硬件加速

给画笔设置属性

mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(getResources().getColor(R.color.dash_line));
// 需要加上这句,否则画不出东西
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(3);
mPaint.setPathEffect(new DashPathEffect(new float[] {15, 5}, 0));

mPath = new Path();

DashPathEffect 接受两个参数 一个是float数组,一个是float数

数组代表 实线长度 和 空白长度 ,比如 {15, 5} :就是15像素实线 5 像素空白 为一组;

float数代表 偏移量,如果不断改变这个值 可以让虚线动起来

最后在onDraw里将path画出来

mPath.reset();
mPath.moveTo(startX, startY);
mPath.lineTo(endX, endY);
canvas.drawPath(mPath, mPaint);