欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Android自定义View实现垂直虚线

Android自定义View实现垂直虚线

2025/6/9 23:41:06 来源:https://blog.csdn.net/qq_36428821/article/details/148410117  浏览:    关键词:Android自定义View实现垂直虚线

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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词