虛線的實現方法
水平虛線的實現:
在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的高度也要大一點,不然虛線顯示不出來
垂直虛線的實現
垂直虛線只需要把水平的旋轉一下即可,不過還需要做一下特殊處理
在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的寬度了
通過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);