Working with Jetpack Compose Canvas

Jetpack Compose provides a flexible and powerful way to draw custom UIs with its Canvas composable. The Canvas lets you draw anything from simple shapes and lines to complex animations and visualizations. In this post, we’ll dive into working with the Compose Canvas, exploring how to draw basic shapes, handle user input, and optimize rendering.

What is Jetpack Compose Canvas?

The Canvas is a fundamental building block in Jetpack Compose for drawing custom graphics. It acts as a drawing board on which you can programmatically render UI elements, offering a low-level yet highly customizable drawing environment. It’s perfect for creating games, data visualizations, or custom UI components beyond what the standard Compose layouts provide.

Why Use Jetpack Compose Canvas?

  • Custom Graphics: Draw any imaginable shape, line, or curve.
  • Interactive UIs: Handle user input, like touch events, to create interactive and dynamic graphics.
  • Animations: Build rich animations by redrawing the Canvas on each frame.
  • Visualization: Display data in compelling ways with charts, graphs, and custom visualizations.

How to Implement Jetpack Compose Canvas

Step 1: Basic Canvas Implementation

Start with the basic Canvas composable and draw simple shapes. Here’s an example to draw a rectangle and a circle:


import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.tooling.preview.Preview

@Composable
fun SimpleCanvasExample() {
    Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        // Draw a rectangle
        drawRect(
            color = Color.Blue,
            topLeft = Offset(100f, 100f),
            size = size / 4f, // Quarter of the canvas size
            style = Stroke(width = 5f)
        )

        // Draw a circle
        drawCircle(
            color = Color.Red,
            center = center,
            radius = size.minDimension() / 8f // Eighth of the canvas size
        )
    }
}

@Preview(showBackground = true)
@Composable
fun SimpleCanvasPreview() {
    SimpleCanvasExample()
}

In this example:

  • We create a Canvas filling the entire available space.
  • Inside the Canvas, we use drawRect and drawCircle to draw a rectangle with a blue stroke and a red filled circle at the center.

Step 2: Drawing Paths

To draw more complex shapes, use the Path API. This lets you define arbitrary lines, curves, and polygons.


import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.tooling.preview.Preview

@Composable
fun PathCanvasExample() {
    Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val path = Path().apply {
            moveTo(100f, 100f)
            lineTo(400f, 100f)
            lineTo(400f, 400f)
            quadraticBezierTo(250f, 500f, 100f, 400f)
            close()
        }

        drawPath(
            path = path,
            color = Color.Green,
            style = Fill
        )
    }
}

@Preview(showBackground = true)
@Composable
fun PathCanvasPreview() {
    PathCanvasExample()
}

This code draws a custom shape using a path with lines and a quadratic Bezier curve:

  • The Path class is used to build a complex shape step-by-step.
  • moveTo starts a new subpath at the specified coordinates.
  • lineTo adds a line segment to the path.
  • quadraticBezierTo adds a quadratic Bezier curve.
  • close closes the path by connecting the end point back to the starting point.
  • drawPath then draws the complete path.

Step 3: Handling User Input

To create interactive UIs, handle touch events. Use the pointerInput modifier to listen for touch events on the Canvas.


import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerEvent

@Composable
fun InteractiveCanvasExample() {
    var touchPosition by remember { mutableStateOf(Offset.Zero) }

    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                awaitPointerEventScope {
                    while (true) {
                        val event: PointerEvent = awaitPointerEvent()
                        val position = event.changes.first().position
                        when (event.type) {
                            PointerEventType.Move -> {
                                touchPosition = position
                            }
                            else -> {}
                        }
                    }
                }
            }
    ) {
        drawCircle(
            color = Color.Magenta,
            center = touchPosition,
            radius = 50f
        )
    }
}

@Preview(showBackground = true)
@Composable
fun InteractiveCanvasPreview() {
    InteractiveCanvasExample()
}

In this interactive example:

  • pointerInput allows the Canvas to listen for touch events.
  • Inside awaitPointerEventScope, we continuously listen for events.
  • Whenever a touch event (PointerEventType.Move) is detected, we update the touchPosition state.
  • The circle is then drawn at the touch position, moving dynamically with the user’s touch.

Step 4: Drawing Images

You can also draw images on the Canvas using drawImage. First, load a Bitmap, and then draw it on the Canvas.


import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.graphics.drawscope.drawImage
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.Color
import com.example.canvasdemo.R

@Composable
fun ImageCanvasExample() {
    val imagePainter: Painter = painterResource(id = R.drawable.android_logo)

    Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        drawImage(
            painter = imagePainter,
            topLeft = Offset(100f, 100f)
        )

        //Draw a border around the image for clarity
        drawRect(
            color = Color.Black,
            topLeft = Offset(100f, 100f),
            size = imagePainter.intrinsicSize,
            style = androidx.compose.ui.graphics.drawscope.Stroke(width = 3f)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun ImageCanvasPreview() {
    ImageCanvasExample()
}

Make sure to place your image asset in the res/drawable directory.

This snippet draws an image onto the Canvas:

  • We load an image from resources using painterResource.
  • The drawImage function draws the loaded image onto the Canvas at a specified position (topLeft).

Advanced Techniques

  • Layers: Use drawIntoCanvas and the Canvas property of drawContext for more advanced drawing operations and custom blending modes.
  • Optimization: For complex drawing, consider using hardware acceleration and caching drawn content as a Picture to improve performance.

Conclusion

The Canvas in Jetpack Compose provides a robust set of tools for drawing custom UIs. Whether you’re creating simple shapes, complex paths, handling user input, or drawing images, the Canvas composable gives you the flexibility you need. Experiment with the different drawing functions, combine them with state management and animations, and build compelling visual experiences in your Android applications.