UI上有一个效果,需要实现垂直的虚线。以下是实现代码:
class VerticalDashedLineView(context: Context, attrs: AttributeSet?)
: View(context, attrs) {private val paint = Paint().apply {color = Color.REDstrokeWidth = 4fpathEffect = DashPathEffect(floatArrayOf(20f, 10f), 0f)
// 20像素实线 + 10像素间隔}override fun onDraw(canvas: Canvas) {super.onDraw(canvas)val centerX = width / 2fcanvas.drawLine(centerX, 0f, centerX, height.toFloat(), paint)}
}
使用:
<com.example.VerticalDashedLineViewandroid:layout_width="4dp"android:layout_height="match_parent" />
Api解释:
- color属性:画笔的颜色(好理解)
- strokeWidth属性:线条宽度
- DashPathEffect的构造函数有两个参数:
float[] intervals
和float phase
。 intervals
数组必须包含偶数个条目(>=2),偶数索引指定“开”间隔,奇数索引指定“关”间隔。phase
参数决定了虚线的起始位置,影响虚线的绘制顺序和位置。- canvas.drawLine(startX, startY, endX, endY, paint)