android绘制虚线

有两种通过xml定义虚线的方法:

方法一

定义drawable_dash_line.xml文件

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="line" xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:color="#979797"
        android:dashWidth="6dp"
        android:dashGap="4dp"
        android:width="1dp"/>
</shape>
  • color:虚线的颜色
  • dashWidth:虚线中的短线长度
  • dashGap:虚线每个短线之间间隔
  • width:表示虚线的“厚度”

使用

<View
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:background="@drawable/drawable_dash_line"
    android:layerType="software"
    />

layerType需要设置为software,否则显示的是一条直线。(硬件加速不支持这种情况,因此需要禁用)。layout_height需要大于上面drawable_dash_line.xml中定义的虚线的width,否则显示不出来。

方法二

定义drawable_dash_line_2.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:left="-5dp" android:top="-5dp" android:right="-5dp" android:bottom="0dp">
        <shape>
            <solid android:color="#ffffff" />
            <stroke
                android:dashGap="5dp"
                android:dashWidth="5dp"
                android:width="1dp"
                android:color="#979797" />
        </shape>
    </item>
</layer-list>

这里利用的是将layer-listitem的各个lefttop之类的属性设置为负值时候可以让这一边显示到View的边框之外(即不可见的地方)来达到只显示某一边的效果。上面定义了除去bottom之外的其他边的margin都为-5dp,这样就只会显示bottom这一条底边,实际上-5dp是随意定义的一个负值,你使用-1dp也是可以的。

layer-list的用法建议参考这篇文章

使用

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@drawable/drawable_dash_line_2"
    />

参考文章:
https://stackoverflow.com/questions/6103713/how-do-i-make-a-dotted-dashed-line-in-android

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文链接:https://github.com/ZQiang94/DashedLine(附源码) 虚线,Demo中...
    毕设邦阅读 4,597评论 0 1
  • 概述 今天我们来探究一下android的样式。其实,几乎所有的控件都可以使用 background属性去引用自定义...
    CokeNello阅读 10,389评论 1 19
  • 系列文章之 Android中自定义View(一)系列文章之 Android中自定义View(二)系列文章之 And...
    YoungerDev阅读 9,060评论 0 9
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,962评论 25 709
  • 1.今天顺利地把武志红的《愿你拥有被爱照亮的生命》这本书看完,太开心了。本来以为十五号之前也完成不了的。开始看《咱...
    华丽的美丽丽阅读 1,103评论 0 0

友情链接更多精彩内容