Compose 动画进阶:Transition 与共享元素

2024-06-27 · 28 min · 动画

Compose 提供了丰富的动画 API,从简单的属性动画到复杂的过渡效果。本文将深入讲解动画的进阶用法。

一、Transition API

val transition = updateTransition(expanded, label = "card")

val cardHeight by transition.animateDp(label = "height") { 
    if (it) 300.dp else 100.dp 
}

val cardColor by transition.animateColor(label = "color") { ... }

二、AnimatedContent

AnimatedContent(
    targetState = count,
    transitionSpec = {
        slideInVertically { it } + fadeIn() togetherWith
            slideOutVertically { -it } + fadeOut()
    }
) { targetCount ->
    Text("$targetCount")
}

三、共享元素动画

SharedTransitionLayout {
    NavHost(...) {
        composable("list") {
            Image(
                modifier = Modifier.sharedElement(
                    state = rememberSharedContentState(key = "image"),
                    animatedVisibilityScope = this
                )
            )
        }
    }
}

四、最佳实践

总结