Courtesy: https://www.andulfgames.com/2017/12/17/parallax-scrolling-background/

[Compose Snippet] Parallax Scroll 🏙

Suraj Sau
ProAndroidDev
Published in
2 min readDec 7, 2020

--

version used for the code snippets

Giving a parallax effect to scrolling views involves a simple concept.

With one view scrolling at the User’s intended speed, the rest of the views should scroll at relatively different rates, in the same direction.

In this case, we’ve a horizontal scroll view with Cards in them. As we scroll horizontally, we intercept the scroll offset of the scroll view and programatically set the displacement offset of the Image inside the Cards.

Our Card view @Composable will need the Scroll view’s x-offset on scrolling.

[1] @Composable Image() alignment’s x-bias is responsible for its positioning within the @Composable ItemCard() . One can adjust this value as per requirement to increase or reduce the displacement speed relative to the scroll view’s scroll speed.

rememberScrollState()

Now, we’ll need to trigger @Composable ItemCard() recomposition in sync with the scroll view’s scroll.

[1] Compose provides a convenient rememberScrollState() to locally ‘remember’ any scroll’s scroll-offset. Here’s a snippet from its documentation,

Create and [remember] the [ScrollState] based on the currently appropriate scroll configuration to allow changing scroll position or observing scroll behavior.

Consider this just as a remember { mutableStateOf(..) } State object. Any child @Composable dependent on it will have its recomposition triggered whenever ScrollState changes value. In this way, we are able to communicate the parent’s scroll-offset to the children.

[2] We are using @Composable ScrollableRow() as the scroll container for the current example. However, any custom @Composable whose Modifier.horizontalScroll(state=..) or Modifier.verticalScroll(state=..) implemented will work just fine.

There you have it. A short snippet on how to listen to scroll offsets and achieve parallax scrolling using Jetpack Compose.

My implementation may not be the most optimised or perfect, but hopefully it could help you with few references to Compose implementations.

I’m documenting all my snippets at a single place. Check out Jetpack Compose over a Cup of Hot Chocolate ☕️

--

--