【问题标题】:Jetpack Compose Draw Line Chart with Circle Dot on each pointJetpack 用每个点上的圆点绘制折线图
【发布时间】:2022-07-25 18:43:46
【问题描述】:

我希望在 Jetpack Compose 的画布上绘制一个折线图,每个点上都有一个小圆圈

折线图完美绘制主要问题是我在每个点上绘制圆点。基本上我使用 quadraticBezierTo() 函数来获得完美曲线,我尝试的代码如下:

Canvas(modifier = modifier) {
    val spacePerHour = (size.width - spacing) / points.size
    var lastX = 0f
    val normX = mutableListOf<Float>()
    val normY = mutableListOf<Float>()

    val strokePath = Path().apply {
        val height = size.height
        for (i in points.indices) {
            val point = points[i]
            val nextInfo = points.getOrNull(i + 1) ?: points.last()
            val leftRatio = (height / 100) * point
            val rightRatio = (height / 100) * nextInfo

            val x1 = spacing + i * spacePerHour
            val y1 = height - spacing - leftRatio.toFloat()
            val x2 = spacing + (i + 1) * spacePerHour
            val y2 = height - spacing - rightRatio.toFloat()
            
            // Circle dot points
            normX.add(x1)
            normY.add(y1)

            if (i == 0) {
                moveTo(x1, y1)
            }

            lastX = (x1 + x2) / 2f

            quadraticBezierTo(
                x1, y1, lastX, (y1 + y2) / 2f
            )
        }
    }
    val fillPath = android.graphics.Path(strokePath.asAndroidPath())
        .asComposePath()
        .apply {
            lineTo(lastX, size.height - spacing)
            lineTo(spacing, size.height - spacing)
            close()
        }
       drawPath(
        path = fillPath,
        brush = Brush.verticalGradient(
            colors = listOf(
                transparentGraphColor,
                Color.Transparent
            ),
            endY = size.height - spacing
        )
    )

    drawPath(
        path = strokePath,
        color = graphColor,
        style = Stroke(
            width = 3.dp.toPx(),
            cap = StrokeCap.Round
        )
    )

    (normX.indices).forEach {
        drawCircle(
            Color.White,
            radius = 3.dp.toPx(),
            center = Offset(normX[it], normY[it])
        )
    }
}

【问题讨论】:

标签: android android-jetpack-compose android-canvas


【解决方案1】:

我建议你使用 Cubic Bézier,在这里你可以找到一个很好的例子:

https://medium.com/@pranjalg2308/understanding-bezier-curve-in-android-and-moddinggraphview-library-a9b1f0f95cd0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多