虛線的實現(xiàn)方法

水平虛線的實現(xiàn):

在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的高度也要大一點,不然虛線顯示不出來


垂直虛線的實現(xiàn)

垂直虛線只需要把水平的旋轉(zhuǎn)一下即可,不過還需要做一下特殊處理

在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" />

注: 如果直接旋轉(zhuǎn)的話,在設置給view的背景后,發(fā)現(xiàn)虛線只有一小段。因為他其實是把水平的直接旋轉(zhuǎn)過來的,你寬度設置的還是原來水平的,寬度設置的小的就會出現(xiàn)一小段的情況

通過item的 left 和 right 屬性來設置左右偏移,水平的線就可以畫出600dp來,然后再旋轉(zhuǎn)成垂直的,這樣就可以自由設置view的寬度了

通過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 接受兩個參數(shù) 一個是float數(shù)組,一個是float數(shù)

數(shù)組代表 實線長度 和 空白長度 ,比如 {15, 5} :就是15像素實線 5 像素空白 為一組;

float數(shù)代表 偏移量,如果不斷改變這個值 可以讓虛線動起來

最后在onDraw里將path畫出來

mPath.reset();
mPath.moveTo(startX, startY);
mPath.lineTo(endX, endY);
canvas.drawPath(mPath, mPaint);
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容