如何在 Jetpack Compose 中实现以下动画?

问题描述 投票:0回答:1

我使用了重量或改变宽度无限动画,但它不是下面gif所示的效果。我如何在 Jetpack Compose 中实现它?

android android-jetpack-compose android-jetpack jetpack
1个回答
0
投票

您可以创建随着进度而改变右侧的形状,并将一个框夹在另一个框上方。

结果

实施

@Composable
private fun BeforeAfterLayout(
    modifier: Modifier = Modifier,
    progress: Float,
    beforeLayout: @Composable BoxScope.() -> Unit,
    afterLayout: @Composable BoxScope.() -> Unit
) {

    val shape = remember(progress) {
        GenericShape { size: Size, layoutDirection: LayoutDirection ->
            addRect(
                rect = Rect(
                    topLeft = Offset.Zero,
                    bottomRight = Offset(size.width * progress, size.height)
                )
            )
        }
    }

    Box(modifier) {
        beforeLayout()

        Box(
            modifier = Modifier.clip(shape)
        ) {
            afterLayout()
        }
    }
}

演示

@Preview
@Composable
private fun BeforeAfterTest() {

    val infiniteTransition = rememberInfiniteTransition("before-after")
    val progress by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(2000, easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        ),
        label = "before-after"
    )

    Column(
        modifier = Modifier.padding(20.dp)
    ) {

        BeforeAfterLayout(
            modifier = Modifier.size(240.dp).border(2.dp, Color.Red),
            progress = progress,
            beforeLayout = {
                Image(
                    modifier = Modifier.fillMaxSize(),
                    painter = painterResource(R.drawable.avatar_1_raster),
                    contentDescription = null,
                    contentScale = ContentScale.FillBounds
                )
            },
            afterLayout = {
                Image(
                    modifier = Modifier.fillMaxSize(),
                    painter = painterResource(R.drawable.avatar_5_raster),
                    contentDescription = null,
                    contentScale = ContentScale.FillBounds
                )
            }
        )

        BeforeAfterLayout(
            progress = progress,
            beforeLayout = {
                Button(
                    onClick = {}
                ) {
                    Text("Before Button")
                }
            },
            afterLayout = {
                Button(
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color.Green
                    ),
                    onClick = {}
                ) {
                    Text("After Button")
                }
            }
        )
    }
}

如果您只想绘制图像,则其他选项是在画布上绘制 2 个图像并更改第二个

dstOffset
函数的
drawImage

还可以作为具有许多自定义选项的库提供。

https://github.com/SmartToolFactory/Compose-BeforeAfter

© www.soinside.com 2019 - 2024. All rights reserved.