Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Animate image size on scroll #390

Merged
merged 5 commits into from
Nov 5, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add simple comments and rename some variables
  • Loading branch information
jakeroseman committed Nov 5, 2024
commit f9875f36e92745dfb019b7d39a894a1814856d51
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,26 @@ import androidx.compose.ui.unit.dp
@Composable
fun ImageResizeOnScrollExample(
modifier: Modifier = Modifier,
maxImgSize: Dp = 300.dp,
minImgSize: Dp = 100.dp
maxImageSize: Dp = 300.dp,
minImageSize: Dp = 100.dp
) {
var currentImgSize by remember { mutableStateOf(maxImgSize) }
var scale by remember { mutableFloatStateOf(1f) }
var currentImageSize by remember { mutableStateOf(maxImageSize) }
var imageScale by remember { mutableFloatStateOf(1f) }

val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Calculate the change in image size based on scroll delta
val delta = available.y
val newImgSize = currentImgSize + delta.dp
val previousImgSize = currentImgSize
val newImageSize = currentImageSize + delta.dp
val previousImageSize = currentImageSize

// Constrain the image size within the allowed bounds
currentImgSize = newImgSize.coerceIn(minImgSize, maxImgSize)
val consumed = currentImgSize - previousImgSize
currentImageSize = newImageSize.coerceIn(minImageSize, maxImageSize)
val consumed = currentImageSize - previousImageSize

// Calculate the scale for the image
scale = currentImgSize / maxImgSize
imageScale = currentImageSize / maxImageSize

// Return the consumed scroll amount
return Offset(0f, consumed.value)
Expand All @@ -65,7 +65,7 @@ fun ImageResizeOnScrollExample(
.fillMaxWidth()
.padding(15.dp)
.offset {
IntOffset(0, currentImgSize.roundToPx())
IntOffset(0, currentImageSize.roundToPx())
}
) {
// Placeholder list items
Expand All @@ -81,12 +81,13 @@ fun ImageResizeOnScrollExample(
painter = ColorPainter(Color.Red),
contentDescription = "Red color image",
Modifier
.size(maxImgSize)
.size(maxImageSize)
.align(Alignment.TopCenter)
.graphicsLayer {
scaleX = scale
scaleY = scale
translationY = -(maxImgSize.toPx() - currentImgSize.toPx()) / 2f
scaleX = imageScale
scaleY = imageScale
// Center the image vertically as it scales
translationY = -(maxImageSize.toPx() - currentImageSize.toPx()) / 2f
}
)
}
Expand Down
Loading