Understanding Canvas in Jetpack Compose

Mayur Waghmare
Mobile Innovation Network
3 min readJul 31, 2024

What is Canvas in Jetpack Compose?

Canvas is a composable function that allows you to draw custom graphics, shapes, and paths on the screen. It provides a flexible way to create complex UI elements, such as charts, graphs, and custom icons.

Understanding X and Y Coordinates on Canvas

  • The top-left corner of the canvas is always (0, 0).
  • The X-axis increases to the right, and the Y-axis increases downwards.
  • Use positive values to move elements to the right and down.
  • Use negative values to move them to the left and up.

Refer the image below.

Get Started with Canvas

To get started with Canvas, add the following dependency to your project.

implementation("androidx.compose.ui:ui:1.6.8")

Drawing Shapes and Paths

Canvas provides a range of drawing functions for creating various shapes and paths. Here are a few examples:

  • drawRect: Draws a rectangle.
  • drawCircle: Draws a circle.
  • drawOval: Draws an oval.
  • drawPath: Draws a custom path.
  • drawLine: Draws a line.

drawRect: Draws a rectangle.

@Composable
fun DrawRectExample() {
Canvas(
modifier = Modifier
.size(200.dp, 200.dp)
) {
drawRect(
topLeft = Offset(50f, 50f),
size = Size(300f, 300f),
color = Color.Gray,
alpha = 1f,
style = Fill
)
}
}

drawCircle: Draws a circle.

@Composable
fun DrawCircleExample() {
Canvas(
modifier = Modifier
.size(200.dp, 200.dp)
) {
drawCircle(
center = Offset(300f, 300f),
radius = 200f,
color = Color.Gray,
alpha = 1f,
style = Fill
)
}
}

drawOval: Draws a oval.

@Composable
fun DrawOvalExample() {
Canvas(
modifier = Modifier
.size(200.dp, 200.dp)
) {
drawOval(
topLeft = Offset(50f, 50f),
size = Size(280f, 400f),
color = Color.Gray,
alpha = 1f,
style = Fill
)
}
}

drawPath: Draws a custom path.

@Composable
fun DrawPathExample() {
Canvas(
modifier = Modifier.size(200.dp, 200.dp)
) {
val path = Path().apply {
moveTo(50f, 50f)
lineTo(300f, 300f)
lineTo(550f, 50f)
close()
}
drawPath(
path = path,
color = Color.Gray,
alpha = 1f,
style = Stroke(8f, cap = StrokeCap.Round)
)
}
}

drawLine: Draws a line.

@Composable
fun DrawLineExample() {
Canvas(
modifier = Modifier.size(200.dp, 200.dp)
) {
drawLine(
start = Offset(50f, 50f),
end = Offset(350f, 50f),
color = Color.Magenta,
alpha = 1f,
strokeWidth = 8f,
cap = StrokeCap.Round
)
}
}

Thank you for taking the time to read this article. If you found the information valuable, please consider giving it a clap or sharing it with others who might benefit from it.

Any Suggestions are welcome. If you need any help or have questions for Code Contact US. You can follow us on LinkedIn for more updates 🔔

--

--

Mayur Waghmare
Mobile Innovation Network

"Mobile App Developer specializing in Android, iOS, and Flutter. Passionate about crafting user-focused, efficient mobile solutions."