一、准备属性
<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"/>