Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
Christina Avatar asked Oct 24 '25 17:10

Christina


1 Answers

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)
    }
}
like image 123
Thracian Avatar answered Oct 26 '25 06:10

Thracian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!