Android Compose : background on Pager

118 Views Asked by At

I have a vertical VerticalPager with 2 pages.

I would like to make a background (for my case it is a gradient which begin on top of page 1 and finish at the bottom of page 2.

It is possible in Android Compose ?

Thank you.

1

There are 1 best solutions below

0
On

Absolutely, it's possible to achieve a vertical gradient background spanning multiple pages in Jetpack Compose. Here's how you can do it:

We'll create a custom modifier that applies the gradient background based on the vertical pager's scroll position.

modifier = Modifier.background {
  val brush = Brush.linearGradient(
    colors = listOf(startColor, endColor),
    start = Offset(0f, 0f), // Top left corner
    end = Offset(0f, Float.POSITIVE_INFINITY), // Bottom of the screen
    tileMode = TileMode.Clamp // Repeat the gradient if content overflows
  )
  val pagerState = rememberPagerState() // Get the pager state
  val offsetY = pagerState.currentPageOffset.value * // Calculate scroll offset ratio
                LocalContentHeight.current // Multiply by content height

  Box(modifier = Modifier.fillMaxSize()) {
    // Draw the gradient behind the content
    Canvas(modifier = Modifier.matchParentSize()) {
      drawRect(brush = brush, size = size, alpha = 0.5f) // Adjust alpha for transparency
    }
    // Place your pager content here
    VerticalPager(count = 2, state = pagerState) {
      // Your page content
    }
  }
}

This approach creates a dynamic background that adjusts the gradient position based on the vertical scroll of the pager. The gradient starts at the top on the first page and transitions to the end color as you scroll down to the second page.