Android自定义View之虚线控件

一、准备属性

<declare-styleable name="DashLineView">
   <attr name="lineColor" format="color"/>
   <attr name="gapWidth" format="dimension"/>
   <attr name="pointHeight" format="dimension"/>
   <attr name="pointWidth" format="dimension"/>
   <attr name="android:orientation" format="string"/>
</declare-styleable>

lineColor 虚线颜色
gapWidth 空隙宽度
pointHeight 虚线中一小节的高度
pointWidth 虚线一小节的宽度
orientation 虚线方向,垂直或者水平

二、继承View

class DashLineView(context: Context,attributeSet: AttributeSet):View(context,attributeSet)

三、获取属性值和初始化画笔

val theme =  context.theme.obtainStyledAttributes(attributeSet, R.styleable.DashLineView,0,0)
gapWidth = theme.getDimension(R.styleable.DashLineView_gapWidth,5.px)
lineColor = theme.getColor(R.styleable.DashLineView_lineColor,Color.BLACK)
pointWidth = theme.getDimension(R.styleable.DashLineView_pointWidth,0f)
pointHeight = theme.getDimension(R.styleable.DashLineView_pointHeight,0f)
theme.getString(R.styleable.DashLineView_android_orientation).log(LogType.TEST)
orientation = if(theme.getString(R.styleable.DashLineView_android_orientation) == "0") LinearLayout.HORIZONTAL else LinearLayout.VERTICAL
theme.recycle()
paint.color = lineColor
paint.isDither = true
paint.style = Paint.Style.STROKE
paint.isAntiAlias = true

四、重写onDraw方法

override fun onDraw(canvas: Canvas?) {
    path.addRect(0f,0f,pointHeight,pointWidth,Path.Direction.CCW)
    paint.pathEffect = PathDashPathEffect(path,gapWidth,0f,PathDashPathEffect.Style.ROTATE)
    if(orientation == LinearLayout.VERTICAL) {
        canvas?.drawLine(
            (width / 2).toFloat(),
            0f,
            (width / 2).toFloat(),
            height.toFloat(),
            paint
        )
    }else{
        canvas?.drawLine(
            0f,
            (height / 2).toFloat(),
            width.toFloat(),
            (height / 2).toFloat(),
            paint
        )
    }
}

path.addRect(0f,0f,pointHeight,pointWidth,Path.Direction.CCW)

这句代码就是定义虚线的一小节的样式,addRect表示是矩形

paint.pathEffect = PathDashPathEffect(path,gapWidth,0f,PathDashPathEffect.Style.ROTATE)

第二个参数gapWidth就是小节之间的空隙,第三个参数表示从多少像素开始绘制,也就是跳跃一段距离。

六、使用

<com.example.test.view.DashLineView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    app:gapWidth="10dp"
    app:pointHeight="4dp"
    app:lineColor="#000"
    app:pointWidth="1dp"
    android:orientation="horizontal"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值