1

I have a problem. When I added the vertical scroll modifier to my canvas, it didn't work. I don't understand why. Code:

Canvas(modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())) {
}

The content just cuts. How do I add scrolling to the canvas?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Christina
  • 55
  • 5

1 Answers1

3

To be able to scroll a Composable with verticalScroll or horizontal scroll content child Composables total width for horizontal scroll total height for vertical scroll should be greater than parent.

You can wrap your Canvas with a Composable and set height of your Canvas bigger than parent or screen as

@Composable
private fun MyCanvas() {
    Box(modifier = Modifier.verticalScroll(rememberScrollState())) {
        Canvas(
            modifier = Modifier
                .border(3.dp, Color.Green)
                .fillMaxWidth()
                .height(2000.dp)

        ) {
            drawCircle(Color.Red)
        }
    }
}

enter image description here

Other option is to use drag or any gesture that returns change in touch position and translating Canvas content.

Canvas(
    modifier = Modifier
        .border(3.dp, Color.Green)
        .fillMaxWidth()
) {

    // You need to change left or top on touch
    // Static values are for demonstration
    translate(left = 0f, top = -1000f) {
        drawCircle(Color.Red)
    }
}
Thracian
  • 43,021
  • 16
  • 133
  • 222