Created
January 12, 2022 15:38
-
-
Save brunogabriel/417f11bbb3f4c876426bd9b1a13c1656 to your computer and use it in GitHub Desktop.
Jetpack Compose - Linear Chart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun LinearChart( | |
modifier: Modifier = Modifier, | |
style: LinearChartStyle = LinearChartStyle.Default, | |
data: List<Int> | |
) { | |
Canvas(modifier = modifier) { | |
// distance between each x point | |
val distance = size.width / (data.size + 1) | |
var currentX = 0F | |
val maxValue = data.maxOrNull() ?: 0 | |
val points = mutableListOf<PointF>() | |
data.forEachIndexed { index, currentData -> | |
if (data.size >= index + 2) { | |
val y0 = (maxValue - currentData) * (size.height / maxValue) | |
val x0 = currentX + distance | |
points.add(PointF(x0, y0)) | |
currentX += distance | |
} | |
} | |
if (style == LinearChartStyle.Default) { | |
for (i in 0 until points.size - 1) { | |
drawLine( | |
start = Offset(points[i].x, points[i].y), | |
end = Offset(points[i + 1].x, points[i + 1].y), | |
color = Color(255, 0, 0), | |
strokeWidth = 8f | |
) | |
} | |
} else { | |
val cubicPoints1 = mutableListOf<PointF>() | |
val cubicPoints2 = mutableListOf<PointF>() | |
for (i in 1 until points.size) { | |
cubicPoints1.add(PointF((points[i].x + points[i - 1].x) / 2, points[i - 1].y)) | |
cubicPoints2.add(PointF((points[i].x + points[i - 1].x) / 2, points[i].y)) | |
} | |
val path = Path() | |
path.moveTo(points.first().x, points.first().y) | |
for (i in 1 until points.size) { | |
path.cubicTo( | |
cubicPoints1[i - 1].x, | |
cubicPoints1[i - 1].y, | |
cubicPoints2[i - 1].x, | |
cubicPoints2[i - 1].y, | |
points[i].x, | |
points[i].y | |
) | |
} | |
drawPath(path, color = Color(255, 0, 0), style = Stroke(width = 8f)) | |
} | |
} | |
} | |
sealed class LinearChartStyle { | |
object Default : LinearChartStyle() | |
object Smooth : LinearChartStyle() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment