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线转向成竖的。