Jetpack compose 如何绘制曲线

Nat*_*tex 5 android android-canvas android-jetpack-compose

有人可以解释一下我如何使用jetpack compose和canvas绘制这条线吗?

在此输入图像描述

ngl*_*ber 5

我不确定您是否想要更有活力的东西,但是这个片段可以给您一些启发。

@ vishal-vasani 评论的文章非常有帮助。

@Composable
fun DrawBrackets() {
    Canvas(
        modifier = Modifier
            .height(200.dp)
            .fillMaxWidth()
    ) {
        val width = size.width
        val height = size.height
        val halfWidth = width.times(.5f)
        val halfHeight = height.times(.5f)

        val startPoints = listOf(
            PointF(0f, 0f),
            PointF(0f, halfHeight),
            PointF(0f, height),

            PointF(width, 0f),
            PointF(width, halfHeight),
            PointF(width, height),
        )

        val path = Path().apply {
            startPoints.forEach { point ->

                val lineEndX =
                    if (point.x > halfWidth)
                        width.minus(halfWidth.times(.3f))
                    else
                        halfWidth.times(.3f)

                val curveXPart1 =
                    if (point.x > halfWidth)
                        width.minus(halfWidth.times(.5f))
                    else
                        halfWidth.times(.5f)

                val curveXPart2 =
                    if (point.x > halfWidth)
                        width.minus(halfWidth.times(.7f))
                    else
                        halfWidth.times(.7f)

                val curve1 = PointF(curveXPart1, point.y)
                val curve2 = PointF(curveXPart1, halfHeight - ((halfHeight - point.y) / 2))

                moveTo(point.x, point.y)
                lineTo(lineEndX, point.y)
                quadraticBezierTo(
                    curve1.x,
                    curve1.y,
                    curve2.x,
                    curve2.y,
                )
                quadraticBezierTo(
                    curveXPart1,
                    halfHeight,
                    curveXPart2,
                    halfHeight,
                )
                lineTo(halfWidth, halfHeight)
            }
        }
        drawPath(
            path = path,
            color = Color.Black,
            style = Stroke(width = 20f, cap = StrokeCap.Round)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述