Android用shape畫個虛線

最近項目中用到了繪製虛線的UI要求,最簡單的當然是設計切圖,直接引入,但是切圖會有屏幕適配拉伸變形的問題,裝逼一點可以使用自定義控件實現,但是代價有點大,所以這裏使用shape實現,簡單做個記錄。

下圖是實現的效果:
在這裏插入圖片描述

第一部分:
是看到的外邊框,這部分相對比較簡單的,drawable中新建一個dash_box.xml文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <!-- 線的寬度,顏色灰色 -->
    <stroke
        android:width="1.5px"
        android:color="@color/c_e8"
        android:dashGap="1dp"
        android:dashWidth="4dp"/>
    <!-- 矩形的圓角半徑 -->
    <corners android:radius="3dp"/>
</shape>

然後在佈局文件中引用就OK:

<LinearLayout
	android:layout_width="match_parent"
	android:layout_height="24dp"
	android:background="@drawable/dash_box">

第二部分是豎線的畫法,新建一個shape_dash_line.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:fromDegrees="90"
            android:visible="true">
            <shape android:shape="line">
                <stroke
                    android:width="1.5px"
                    android:color="@color/c_e8"
                    android:dashWidth="4dp"
                    android:dashGap="1dp"/>
            </shape>
        </rotate>
    </item>
</layer-list>

然後在佈局中引用圖片資源:

<View
	android:layout_width="1.5px"
	android:layout_height="match_parent"
	android:background="@drawable/shape_dash_line"
	android:layerType="software"/>

PS:
android:layerType="software"這句一定要加上,否則看到的是一條直線;
rotate標籤實現將普通的shape線轉向成豎的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章