Create custom graphics with Compose Canvas!
Basic Shapes -drawRect, drawCircle, drawLine
Canvas(modifier = Modifier.fillMaxSize()) {
// Draw a rectangle
drawRect(
color = Color.Blue,
topLeft = Offset(50f, 50f),
size = Size(100f, 100f)
)
// Draw a circle
drawCircle(
color = Color.Red,
radius = 40f,
center = Offset(300f, 300f)
)
// Draw a line
drawLine(
color = Color.Green,
start = Offset(0f, 0f),
end = Offset(500f, 500f),
strokeWidth = 4f
)
}
Progress Rings with drawArc
Create circular progress indicators:
Canvas(modifier = Modifier.size(200.dp)) {
val radius = 80.dp.toPx()
val center = Offset(100.dp.toPx(), 100.dp.toPx())
drawArc(
color = Color.LightGray,
startAngle = 0f,
sweepAngle = 360f,
useCenter = false,
topLeft = center - Offset(radius, radius),
size = Size(radius * 2, radius * 2),
style = Stroke(width = 8.dp.toPx())
)
drawArc(
color = Color.Blue,
startAngle = 0f,
sweepAngle = 270f,
useCenter = false,
topLeft = center - Offset(radius, radius),
size = Size(radius * 2, radius * 2),
style = Stroke(width = 8.dp.toPx())
)
}
Star Shapes with Path
Use Path for complex shapes:
Canvas(modifier = Modifier.size(200.dp)) {
val path = Path().apply {
moveTo(100f, 0f)
repeat(4) {
lineTo(100 + 40 * kotlin.math.cos((it + 1) * Math.PI / 2),
0 + 40 * kotlin.math.sin((it + 1) * Math.PI / 2))
}
close()
}
drawPath(path, color = Color.Yellow)
}
Animated Drawing with infiniteTransition
Animate canvas operations:
val infiniteTransition = rememberInfiniteTransition()
val angle by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(tween(2000))
)
Canvas(modifier = Modifier.fillMaxSize()) {
drawArc(
color = Color.Blue,
startAngle = angle,
sweepAngle = 180f,
useCenter = true
)
}
nativeCanvas for Text
Draw text directly on canvas:
Canvas(modifier = Modifier.fillMaxSize()) {
val nativeCanvas = drawContext.canvas.nativeCanvas
val paint = android.graphics.Paint().apply {
color = android.graphics.Color.BLACK
textSize = 48f
}
nativeCanvas.drawText("Custom Text", 50f, 100f, paint)
}
Master canvas drawing to create stunning custom UIs!
8 production-ready Android app templates on Gumroad.
Browse templates → Gumroad
Top comments (0)