Android中使用Drawable绘制横竖虚线

横虚线

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    
    <stroke
        android:color="#AAAAAA"
        android:dashGap="2dp"
        android:dashWidth="4dp"
        android:width="1dp"/>
</shape>

dashGap: 虚线间隔
dashWidth:虚线长度
width:虚线的粗细

  • 把虚线的 drawable 设置为某个 View 的 background 时,需要加上android:layerType="software",不然真机上只会显示实线
  • View 的高度要大于虚线的 width,否则无法显示虚线

竖虚线

shape 不支持竖虚线,因此需要使用 rotate 进行旋转:

<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90">
    
    <shape android:shape="line">
    
        <stroke
           android:color="#AAAAAA"
          android:dashGap="2dp"
           android:dashWidth="4dp"
          android:width="1dp"/>
    </shape>
</rotate>

系统会先画一条横虚线再进行顺时针90°旋转,因此会有一种问题:虚线的长度跟 View 的宽度有关,因为它需要在 View 上根据宽度画出虚线,这时就决定了虚线的长度,旋转后长度也不会变化了。

有一个方法就是利用 layer-list:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   
    <item
        android:left="-300dp"
        android:right="-300dp">
        
        <rotate
            android:fromDegrees="90">
            
            <shape android:shape="line">
                
                <stroke
                    android:color="#AAAAAA"
                    android:dashGap="2dp"
                    android:dashWidth="4dp"
                    android:width="1dp"/>
            </shape>
        </rotate>
    </item>
</layer-list>

这里设置了 item 的偏移量,左右各 -300,这样就可以画出 -600 的竖虚线。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值