Canvas in Jetpack Compose provides low-level drawing capabilities for custom graphics, charts, and animations.
Drawing Basic Shapes
@Composable
fun CanvasDrawing() {
Canvas(modifier = Modifier.fillMaxSize()) {
// Draw circle
drawCircle(
color = Color.Blue,
radius = 100f,
center = Offset(size.width / 2, size.height / 2)
)
// Draw rectangle
drawRect(
color = Color.Red,
topLeft = Offset(100f, 100f),
size = Size(200f, 150f)
)
// Draw line
drawLine(
color = Color.Black,
start = Offset(0f, 0f),
end = Offset(size.width, size.height),
strokeWidth = 5f
)
}
}
Creating Paths and Gradients
@Composable
fun PathDrawing() {
Canvas(modifier = Modifier.size(200.dp)) {
val path = Path().apply {
moveTo(0f, 0f)
lineTo(size.width, 0f)
lineTo(size.width, size.height)
lineTo(0f, size.height)
close()
}
drawPath(
path = path,
color = Color.Green,
style = Stroke(width = 2f)
)
// Gradient fill
val gradient = Brush.linearGradient(
colors = listOf(Color.Blue, Color.Green),
start = Offset(0f, 0f),
end = Offset(size.width, size.height)
)
drawRect(brush = gradient)
}
}
Simple Bar Chart
@Composable
fun BarChart(data: List<Float>) {
Canvas(modifier = Modifier.fillMaxWidth().height(300.dp)) {
val barWidth = size.width / data.size
val maxValue = data.maxOrNull() ?: 1f
data.forEachIndexed { index, value ->
val barHeight = (value / maxValue) * size.height
drawRect(
color = Color.Blue,
topLeft = Offset(index * barWidth, size.height - barHeight),
size = Size(barWidth - 4f, barHeight)
)
}
}
}
Canvas drawing enables unlimited creative possibilities in your Compose apps.
8 Android app templates available on Gumroad
Top comments (0)