如何在HorizontalPager分页切换时添加图片平滑过渡动画
你当前直接仅渲染对应currentIndex的单张背景图,切换页面时会直接替换图片,没有过渡效果。要实现背景随滑动同步渐变的效果,修改方案如下:
val pagerState = rememberPagerState(pageCount = 3) val poster = listOf( R.drawable.red, R.drawable.blue, R.drawable.green ) Box(modifier = Modifier.fillMaxSize()) { // 背景渐变实现部分 val currentPage = pagerState.currentPage val offset = pagerState.currentPageOffset // 渲染当前页背景 Image( painter = painterResource(poster[currentPage]), contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .fillMaxWidth() .alpha(1 - offset.absoluteValue) ) // 渲染即将进入的页背景 val nextPage = if (offset > 0) currentPage + 1 else currentPage - 1 if (nextPage in poster.indices) { Image( painter = painterResource(poster[nextPage]), contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .fillMaxWidth() .alpha(offset.absoluteValue) ) } HorizontalPager( state = pagerState, modifier = Modifier.fillMaxSize() ) { page -> val maxOffset = 70.dp val offsetAnim = maxOffset * when (page) { pagerState.currentPage -> { pagerState.currentPageOffset.absoluteValue } pagerState.currentPage - 1 -> { 1 + pagerState.currentPageOffset.coerceAtMost(0f) } pagerState.currentPage + 1 -> { 1 - pagerState.currentPageOffset.coerceAtLeast(0f) } else -> { 1f } } Card( modifier = Modifier .fillMaxWidth(0.7f) .fillMaxHeight(0.7f) .padding(22.dp) .offset(y = offsetAnim), shape = RoundedCornerShape(30.dp), elevation = 110.dp ) {} } }
修改说明
- 背景区域同时渲染当前页和下一页/上一页的两张图片,通过滑动偏移量动态控制两张图的透明度,实现交叉溶解的过渡效果,和目标动画效果一致
- 原有卡片的上下浮动交互逻辑完全保留,不需要额外修改
内容的提问来源于stack exchange,提问作者ABINASH KUMAR
相关产品推荐
相关产品推荐

