最近项目中用到了绘制虚线的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文件:

本文介绍了如何在Android中使用shape资源文件来绘制虚线,避免了屏幕适配问题和自定义控件的复杂性。通过创建dash_box.xml和shape_dash_line.xml文件,实现了虚线边框和竖线效果,并提示了android:layerType="software"的重要性。
最低0.47元/天 解锁文章
731

被折叠的 条评论
为什么被折叠?



