首页 > 解决方案 > 如何使用 HorizantalPager 为图像设置动画?

问题描述

我在 Box 中有三个背景,该框包含 Horizo​​ntalPager 和一个根据 Horizo​​ntalPager 当前页面更改的图像组件,但没有动画如何添加这样的动画
https://cdn.dribbble.com/users/1588664/screenshots/8257559 /media/d94b36cb7822008df8055c90ca6e2238.mp4

这是我的代码预览 https://drive.google.com/file/d/1i2ix1Xdx-TK2SVPgx8MhFZWfqQnhZcr5/view?usp=sharing

val pagerState = rememberPagerState(pageCount = 3)
val currentIndex = pagerState.currentPage
val currentPageOffset = pagerState.currentPageOffset
val poster = listOf(
    R.drawable.red,R.drawable.blue,R.drawable.green
)
Box(modifier = Modifier.fillMaxSize()){
    Image(
        painter = painterResource(poster[currentIndex]),
        contentDescription = null,
        contentScale = ContentScale.FillWidth,
        modifier = Modifier.fillMaxWidth()
    )
    HorizontalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize()
    ) { page ->
        val maxOffset = 70.dp
        val offset = maxOffset * when (page) {
            currentIndex -> {
                currentPageOffset.absoluteValue
            }
            currentIndex - 1 -> {
                1 + currentPageOffset.coerceAtMost(0f)
            }
            currentIndex + 1 -> {
                1 - currentPageOffset.coerceAtLeast(0f)
            }
            else -> {
                1f
            }
        }
        Card(
            modifier = Modifier
                .fillMaxWidth(0.7f)
                .fillMaxHeight(0.7f)
                .padding(22.dp)
                .offset(y = offset),
            shape = RoundedCornerShape(30.dp),
            elevation = 110.dp
        ) {}
    }
}

标签: android-jetpack-compose

解决方案


推荐阅读