使用 getSegment 逐步绘制路径

Draw a path progressively with getSegment

我创建了一个自定义视图来画一条线,但是是渐进的。我尝试使用PathMeasure和getSegment,但效果不佳。它只是一直用最终尺寸画线。

private val paint = Paint().apply {
    isAntiAlias = true
    color = Color.WHITE
    style = Paint.Style.STROKE
    strokeWidth = 10f
}


override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)

    val path = Path().apply {
        moveTo(width/2.toFloat(), height/2.toFloat())
        lineTo(width/2.toFloat(), height/4.toFloat())
    }

    val measure = PathMeasure(path, false)
    val length = measure.length
    val partialPath = Path()
    measure.getSegment(0.0f, length, partialPath, true)
    partialPath.rLineTo(0.0f, 0.0f)
    canvas!!.drawPath(partialPath, paint)
}

你可以用 DashPathEffect 做到这一点

DashPathEffect dashPathEffect = new DashPathEffect(new float[]{1000.0f,9999999},0);
Paint.setPathEffect(dashPathEffect);

将 1000 更改为您的长度(Dash 中的 "on" 个部分)

并将 99999999 设置为最大值(Dash 中的 "off" 个部分)

请使用此参数并阅读此 article

正如@mohandes 所解释的那样,这是我的制作方法:

private var path = Path()
private var paint = Paint()
private val dashes = floatArrayOf(125f, 125f)

init {

    paint = Paint().apply {
        isAntiAlias = true
        color = Color.WHITE
        style = Paint.Style.STROKE
        strokeWidth = 10.0f
        pathEffect = CornerPathEffect(8f)
    }

    path = Path().apply {
        moveTo(312f, 475f)
        lineTo(312f, 375f)
    }


    val lineAnim = ValueAnimator.ofFloat(100f, 0f)
    lineAnim.interpolator = LinearInterpolator()
    lineAnim.addUpdateListener {
        paint.pathEffect = ComposePathEffect(DashPathEffect(dashes, lineAnim.animatedValue as Float), CornerPathEffect(8f))
        invalidate()
    }

    lineAnim.duration = 1000
    lineAnim.start()
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas!!.drawPath(path, paint)
}