Search code examples
androidcanvasscrollandroid-jetpack-composeandroid-jetpack

Vertical scroll on Canvas (Jetpack Compose)


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?


Solution

  • 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)
        }
    }