【发布时间】: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