Android竖虚线绘制

在Android开发中,为了创建竖向虚线作为分隔线,通常需要在drawable资源目录下自定义XML来实现。文章介绍了如何通过旋转水平虚线实现竖直效果,并提供了设置view宽度、margin以及layerType属性为software的技巧,以确保虚线正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android UI制作中,经常会需要一些线条作为分隔线,一般做个width或height为1dp的view就可以解决了,如果需要虚线,则需要在drawable目录自定义xml进行绘制了,一般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="@color/white"
        android:dashWidth="5dp"
        android:dashGap="2dp" />
</shape>

然后在需要画虚线的地方使用该drawable作为背景即可。

不过如果需要一条竖虚线,就麻烦很多。

首先,同样定义xml文件,不过要旋转90度,这样就是竖的了:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90">
    <shape android:shape="line">
        <stroke
            android:width="1dp"
            android:color="@color/white"
            android:dashWidth="5dp"
            android:dashGap="2dp"
            />
    </shape>
</rotate>

另外,在使用该drawable时,宽度不能设为1dp,因为这个宽度是旋转前的虚线长度,如果设为1dp,则看不出虚线了,所以需要一点小技巧:

1)在view的宽度设大一些,然后设置marginLeft 和marginRight 为负值,就不会影响到旁边的view了

        <View
            android:background="@drawable/dot_line_white"
            android:layout_marginLeft="-10dp"
            android:layout_marginRight="-10dp"
            android:layerType="software"
            android:layout_width="50dp"
            android:layout_height="match_parent"/>

2)使用FrameLayout等布局方式,将虚线view置于其他view之上。

注意:设置时必须设置layerType为software,否则手机显示不会显示出虚线。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值