Compose 卡片叠加效果实现

475 阅读1分钟

Compose 卡片叠加效果实现

找案例过程

rememberSwipeableState rememberSwipeToDismissBoxState rememberSwipeToDismissBoxState

实现思路

  1. 根据上述案例找到侧滑取消代码
  2. 去掉已取消卡片,数量减1,调整剩余卡片大小
  3. 卡片叠加用Box包裹实现,相当于帧布局
  4. 设置背景透明,左右边距和纵向偏移实现错位效果
  5. 实现代码预计效果展示
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SwipeableSample() {
    var step = 4.dp
    var cardSize by remember {
        mutableStateOf(8)
    }

    repeat(cardSize) {
        val state = rememberSwipeToDismissBoxState()
        if (state.currentValue.ordinal == 2) {
            SwipeToDismissBox(
                state = state, backgroundContent = {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Transparent)
                    )
                }
            ) {
                ElevatedCard(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(
                            horizontal = 24.dp
                                .plus(step.value.times(cardSize - it).dp),
                            vertical = 96.dp
                        )
                        .offset(0.dp, y = -it.times(step.value).dp),
                    shape = RoundedCornerShape(8.dp), elevation = CardDefaults.elevatedCardElevation(),
                    colors = CardDefaults.cardColors(
                        containerColor = if (it % 2 == 0) Color(0xFF7c1823) else MaterialTheme.colorScheme.primary
                    )
                ) {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
//                        verticalArrangement = Arrangement.Center,
                    ) {
                        Spacer(Modifier.size(36.dp))
                        Image(imageVector = Icons.Default.Face, contentDescription = "avatar", modifier = Modifier.size(80.dp), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(Color.White))
                        Spacer(Modifier.size(24.dp))
                        Text("Swipe to dismiss", color = Color.White)
                    }

                }
            }
        } else {
            cardSize -= 1
        }
    }



}
Screen_recording_20240217_113654 00_00_00-00_00_30.gif