Compose 中的动画快速指南

Compose 具有许多内置的动画机制,知道该选择哪种机制可能会令人不知所措。下面列出了常见的动画用例。如需详细了解可用的一整套不同 API 选项,请参阅完整的 Compose 动画文档

为常见的可组合属性添加动画效果

Compose 提供了方便的 API,可用于解决许多常见的动画用例。本部分展示了如何为可组合项的常见属性添加动画效果。

为出现 / 消失添加动画效果

显示和隐藏自身的绿色可组合项
图 1. 在 Column 中某个项的出现和消失添加动画效果

使用 AnimatedVisibility 可隐藏或显示可组合项。AnimatedVisibility 中的子项可以使用 Modifier.animateEnterExit() 实现自己的进入或退出过渡。

var visible by remember {
    mutableStateOf(true)
}
// Animated visibility will eventually remove the item from the composition once the animation has finished.
AnimatedVisibility(visible) {
    // your composable here
    // ...
}

借助 AnimatedVisibility 的 Enter 和 exit 参数,您可以配置可组合项在出现和消失时的行为方式。如需了解详情,请参阅完整文档

为可组合项的可见性添加动画效果的另一种方法是,使用 animateFloatAsState 为一段时间内的 alpha 值添加动画效果:

var visible by remember {
    mutableStateOf(true)
}
val animatedAlpha by animateFloatAsState(
    targetValue = if (visible) 1.0f else 0f,
    label = "alpha"
)
Box(
    modifier = Modifier
        .size(200.dp)
        .graphicsLayer {
            alpha = animatedAlpha
        }
        .clip(RoundedCornerShape(8.dp))
        .background(colorGreen)
        .align(Alignment.TopCenter)
) {
}

不过,更改 alpha 时需要注意,可组合项仍会保留在组合中,并且将继续占用其布局的空间。这可能会导致屏幕阅读器和其他无障碍机制仍考虑屏幕上的内容。另一方面,AnimatedVisibility 最终会从组合中移除该项。

为可组合项的 Alpha 添加动画效果
图 2. 为可组合项的 Alpha 添加动画效果

为背景颜色添加动画效果

背景颜色会随时间而变化的可组合项,以动画形式呈现,其中颜色会逐渐淡化。
图 3. 为可组合项的背景颜色添加动画效果

val animatedColor by animateColorAsState(
    if (animateBackgroundColor) colorGreen else colorBlue,
    label = "color"
)
Column(
    modifier = Modifier.drawBehind {
        drawRect(animatedColor)
    }
) {
    // your composable here
}

此选项比使用 Modifier.background() 性能更高。Modifier.background() 对于单样本颜色设置是可接受的,但在为颜色随时间的推移添加动画效果时,这可能会导致不必要的重组。

如需无限地为背景颜色添加动画效果,请参阅重复动画部分

为可组合项的大小添加动画效果

绿色可组合项,以动画形式平稳地改变其大小。
图 4. 可组合项在较小尺寸和较大尺寸之间平滑地添加动画效果

借助 Compose,您可以通过几种不同的方式为可组合项的大小添加动画效果。对于可组合项大小变化之间的动画,使用 animateContentSize()

例如,如果您的框包含可以从一行展开到多行的文本,则可以使用 Modifier.animateContentSize() 实现更顺畅的过渡:

var expanded by remember { mutableStateOf(false) }
Box(
    modifier = Modifier
        .background(colorBlue)
        .animateContentSize()
        .height(if (expanded) 400.dp else 200.dp)
        .fillMaxWidth()
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            expanded = !expanded
        }

) {
}

您还可以使用 AnimatedContent,以及 SizeTransform 来描述应如何发生大小变化。

为可组合项的位置添加动画效果

绿色可组合项顺畅地向下和向右移动动画
图 5. 可按偏移量移动的可组合项

如需为可组合项的位置添加动画效果,请结合使用 Modifier.offset{ }animateIntOffsetAsState()

var moved by remember { mutableStateOf(false) }
val pxToMove = with(LocalDensity.current) {
    100.dp.toPx().roundToInt()
}
val offset by animateIntOffsetAsState(
    targetValue = if (moved) {
        IntOffset(pxToMove, pxToMove)
    } else {
        IntOffset.Zero
    },
    label = "offset"
)

Box(
    modifier = Modifier
        .offset {
            offset
        }
        .background(colorBlue)
        .size(100.dp)
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            moved = !moved
        }
)

如果您想确保在为位置或大小添加动画效果时,系统不会在其他可组合项之上或之下绘制可组合项,请使用 Modifier.layout{ }。此修饰符会将尺寸和位置更改传播给父级,而父级又会影响其他子级。

例如,如果您要在 Column 内移动 Box,并且其他子项需要在 Box 移动时移动,请使用 Modifier.layout{ } 添加偏移量信息,如下所示:

var toggled by remember {
    mutableStateOf(false)
}
val interactionSource = remember {
    MutableInteractionSource()
}
Column(
    modifier = Modifier
        .padding(16.dp)
        .fillMaxSize()
        .clickable(indication = null, interactionSource = interactionSource) {
            toggled = !toggled
        }
) {
    val offsetTarget = if (toggled) {
        IntOffset(150, 150)
    } else {
        IntOffset.Zero
    }
    val offset = animateIntOffsetAsState(
        targetValue = offsetTarget, label = "offset"
    )
    Box(
        modifier = Modifier
            .size(100.dp)
            .background(colorBlue)
    )
    Box(
        modifier = Modifier
            .layout { measurable, constraints ->
                val offsetValue = if (isLookingAhead) offsetTarget else offset.value
                val placeable = measurable.measure(constraints)
                layout(placeable.width + offsetValue.x, placeable.height + offsetValue.y) {
                    placeable.placeRelative(offsetValue)
                }
            }
            .size(100.dp)
            .background(colorGreen)
    )
    Box(
        modifier = Modifier
            .size(100.dp)
            .background(colorBlue)
    )
}

有两个框,其中第二个框以动画方式呈现其 X、Y 位置,第三个框也会通过自身移动 Y 量来做出响应。
图 6. 使用 Modifier.layout{ } 添加动画效果

为可组合项的内边距添加动画效果

绿色可组合项在点击时越来越小,并且内边距以动画形式呈现
图 7. 可组合项及其内边距动画效果

如需为可组合项的内边距添加动画效果,请结合使用 animateDpAsStateModifier.padding()

var toggled by remember {
    mutableStateOf(false)
}
val animatedPadding by animateDpAsState(
    if (toggled) {
        0.dp
    } else {
        20.dp
    },
    label = "padding"
)
Box(
    modifier = Modifier
        .aspectRatio(1f)
        .fillMaxSize()
        .padding(animatedPadding)
        .background(Color(0xff53D9A1))
        .clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            toggled = !toggled
        }
)

为可组合项的高度添加动画效果

图 8.可组合项的高度在点击时添加动画效果

如需为可组合项的高度添加动画效果,请结合使用 animateDpAsStateModifier.graphicsLayer{ }。对于一次性高度变化,请使用 Modifier.shadow()。如果要为阴影添加动画效果,使用 Modifier.graphicsLayer{ } 修饰符是效果更好的选项。

val mutableInteractionSource = remember {
    MutableInteractionSource()
}
val pressed = mutableInteractionSource.collectIsPressedAsState()
val elevation = animateDpAsState(
    targetValue = if (pressed.value) {
        32.dp
    } else {
        8.dp
    },
    label = "elevation"
)
Box(
    modifier = Modifier
        .size(100.dp)
        .align(Alignment.Center)
        .graphicsLayer {
            this.shadowElevation = elevation.value.toPx()
        }
        .clickable(interactionSource = mutableInteractionSource, indication = null) {
        }
        .background(colorGreen)
) {
}

或者,使用 Card 可组合项,并根据状态将高度属性设为不同的值。

为文本缩放、平移或旋转添加动画效果

文本可组合项说
图 9. 在两种尺寸之间流畅地以动画形式呈现文本

为文本的缩放、平移或旋转添加动画效果时,请将 TextStyle 上的 textMotion 参数设置为 TextMotion.Animated。这样可以确保文本动画之间的过渡更流畅。使用 Modifier.graphicsLayer{ } 可平移、旋转或缩放文本。

val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
val scale by infiniteTransition.animateFloat(
    initialValue = 1f,
    targetValue = 8f,
    animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
    label = "scale"
)
Box(modifier = Modifier.fillMaxSize()) {
    Text(
        text = "Hello",
        modifier = Modifier
            .graphicsLayer {
                scaleX = scale
                scaleY = scale
                transformOrigin = TransformOrigin.Center
            }
            .align(Alignment.Center),
        // Text composable does not take TextMotion as a parameter.
        // Provide it via style argument but make sure that we are copying from current theme
        style = LocalTextStyle.current.copy(textMotion = TextMotion.Animated)
    )
}

为文本颜色添加动画效果

字词
图 10. 展示为文本颜色添加动画效果的示例

如需为文本颜色添加动画效果,请在 BasicText 可组合项上使用 color lambda:

val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
val animatedColor by infiniteTransition.animateColor(
    initialValue = Color(0xFF60DDAD),
    targetValue = Color(0xFF4285F4),
    animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
    label = "color"
)

BasicText(
    text = "Hello Compose",
    color = {
        animatedColor
    },
    // ...
)

在不同类型的内容之间切换

绿幕说
图 11. 使用 AnimatedContent 为不同可组合项之间的变化添加动画效果(速度变慢)

使用 AnimatedContent 在不同的可组合项之间添加动画效果;如果您只是想在可组合项之间进行标准淡入淡出,请使用 Crossfade

var state by remember {
    mutableStateOf(UiState.Loading)
}
AnimatedContent(
    state,
    transitionSpec = {
        fadeIn(
            animationSpec = tween(3000)
        ) togetherWith fadeOut(animationSpec = tween(3000))
    },
    modifier = Modifier.clickable(
        interactionSource = remember { MutableInteractionSource() },
        indication = null
    ) {
        state = when (state) {
            UiState.Loading -> UiState.Loaded
            UiState.Loaded -> UiState.Error
            UiState.Error -> UiState.Loading
        }
    },
    label = "Animated Content"
) { targetState ->
    when (targetState) {
        UiState.Loading -> {
            LoadingScreen()
        }
        UiState.Loaded -> {
            LoadedScreen()
        }
        UiState.Error -> {
            ErrorScreen()
        }
    }
}

您可以自定义 AnimatedContent,以显示多种不同类型的进入和退出过渡。如需了解详情,请参阅有关 AnimatedContent 的文档或阅读这篇关于 AnimatedContent 的博文。

在导航到不同目的地的同时添加动画效果

两个可组合项,一个绿色表示“着陆”,另一个蓝色表示“详细信息”,通过将详情可组合项滑动到着陆可组合项上来实现动画效果。
图 12. 使用 navigation-compose 在可组合项之间添加动画效果

如需在使用 navigation-compose 工件时为可组合项之间的过渡添加动画效果,请在可组合项上指定 enterTransitionexitTransition。您还可以在顶级 NavHost 中设置要用于所有目的地的默认动画:

val navController = rememberNavController()
NavHost(
    navController = navController, startDestination = "landing",
    enterTransition = { EnterTransition.None },
    exitTransition = { ExitTransition.None }
) {
    composable("landing") {
        ScreenLanding(
            // ...
        )
    }
    composable(
        "detail/{photoUrl}",
        arguments = listOf(navArgument("photoUrl") { type = NavType.StringType }),
        enterTransition = {
            fadeIn(
                animationSpec = tween(
                    300, easing = LinearEasing
                )
            ) + slideIntoContainer(
                animationSpec = tween(300, easing = EaseIn),
                towards = AnimatedContentTransitionScope.SlideDirection.Start
            )
        },
        exitTransition = {
            fadeOut(
                animationSpec = tween(
                    300, easing = LinearEasing
                )
            ) + slideOutOfContainer(
                animationSpec = tween(300, easing = EaseOut),
                towards = AnimatedContentTransitionScope.SlideDirection.End
            )
        }
    ) { backStackEntry ->
        ScreenDetails(
            // ...
        )
    }
}

有许多不同类型的进入和退出过渡对传入和传出内容应用不同的效果,请参阅相关文档了解详情。

重复播放动画

通过在这两种颜色之间添加动画效果无限转换,将绿色背景转换为蓝色背景。
图 13. 背景颜色在两个值之间无限添加动画效果

结合使用 rememberInfiniteTransitioninfiniteRepeatable animationSpec 可持续重复播放动画。更改了 RepeatModes 以指定其切换方式。

使用 finiteRepeatable 可重复指定次数。

val infiniteTransition = rememberInfiniteTransition(label = "infinite")
val color by infiniteTransition.animateColor(
    initialValue = Color.Green,
    targetValue = Color.Blue,
    animationSpec = infiniteRepeatable(
        animation = tween(1000, easing = LinearEasing),
        repeatMode = RepeatMode.Reverse
    ),
    label = "color"
)
Column(
    modifier = Modifier.drawBehind {
        drawRect(color)
    }
) {
    // your composable here
}

在启动可组合项时启动动画

LaunchedEffect 在可组合项进入组合时运行。它会在可组合项启动时启动动画,您可以使用它来推动动画状态的变化。结合使用 AnimatableanimateTo 方法,以在启动时启动动画:

val alphaAnimation = remember {
    Animatable(0f)
}
LaunchedEffect(Unit) {
    alphaAnimation.animateTo(1f)
}
Box(
    modifier = Modifier.graphicsLayer {
        alpha = alphaAnimation.value
    }
)

创建依序动画

四个圆圈,各个圆圈之间有绿色箭头,逐一呈现动画效果。
图 14. 表示依序动画如何逐个播放的示意图。

使用 Animatable 协程 API 执行依序或并发动画。连续对 Animatable 调用 animateTo 会导致每个动画等待前面的动画完成后再继续。这是因为它属于挂起函数。

val alphaAnimation = remember { Animatable(0f) }
val yAnimation = remember { Animatable(0f) }

LaunchedEffect("animationKey") {
    alphaAnimation.animateTo(1f)
    yAnimation.animateTo(100f)
    yAnimation.animateTo(500f, animationSpec = tween(100))
}

创建并发动画

三个圆圈带有绿色箭头,每个圆圈以动画形式显示,同时全部呈现动画效果。
图 15.表示并发动画如何同时进度的示意图。

使用协程 API(Animatable#animateTo()animate)或 Transition API 来实现并发动画。如果您在协程上下文中使用多个启动函数,则协程会同时启动动画:

val alphaAnimation = remember { Animatable(0f) }
val yAnimation = remember { Animatable(0f) }

LaunchedEffect("animationKey") {
    launch {
        alphaAnimation.animateTo(1f)
    }
    launch {
        yAnimation.animateTo(100f)
    }
}

您可以使用 updateTransition API 使用相同的状态同时驱动许多不同的属性动画。以下示例为由状态变化控制的两个属性(rectborderWidth)添加动画效果:

var currentState by remember { mutableStateOf(BoxState.Collapsed) }
val transition = updateTransition(currentState, label = "transition")

val rect by transition.animateRect(label = "rect") { state ->
    when (state) {
        BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
        BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
    }
}
val borderWidth by transition.animateDp(label = "borderWidth") { state ->
    when (state) {
        BoxState.Collapsed -> 1.dp
        BoxState.Expanded -> 0.dp
    }
}

优化动画性能

Compose 中的动画可能会导致性能问题。这取决于动画的本质:快速移动或改变屏幕上的像素,每帧一帧,以创造运动的错觉。

请考虑 Compose 的不同阶段:组合、布局和绘制。如果您的动画更改了布局阶段,则所有受影响的可组合项都需要重新布局和重新绘制。如果动画发生在绘制阶段,则默认情况下,其性能会比在布局阶段运行动画时更高,因为这样可减少整体工作量。

为确保应用在添加动画效果时尽可能少地执行事务,请尽可能选择 Modifier 的 lambda 版本。这样会跳过重组,并在组合阶段之外执行动画,否则请使用 Modifier.graphicsLayer{ },因为此修饰符始终在绘制阶段运行。如需了解详情,请参阅性能文档中的延迟读取部分。

更改动画时间设置

默认情况下,Compose 为大多数动画使用弹簧动画。弹簧或基于物理特性的动画让人感觉更自然。它们也是可以中断的,因为它们会考虑对象当前的速度,而不是固定时间。如果要替换默认值,上面演示的所有动画 API 都可以设置 animationSpec,以自定义动画的运行方式,无论您希望动画在特定时长内执行还是提高弹性。

下面总结了不同的 animationSpec 选项:

  • spring:基于物理特性的动画,所有动画的默认设置。您可以更改刚度或阻尼比,以实现不同的动画外观和风格。
  • tween(“Between”的缩写):基于时长的动画,使用 Easing 函数在两个值之间添加动画效果。
  • keyframes:用于指定动画中某些关键点处的值的规范。
  • repeatable:基于时长的规范,运行一定次数,由 RepeatMode 指定。
  • infiniteRepeatable:基于时长的规范,无限期运行。
  • snap:即时贴靠结束值,而不显示任何动画。
在此处填写替代文本
图 16.未设置任何规范,而未设置自定义 Spring 规范

如需详细了解 AnimationSpecs,请参阅完整文档。

其他资源

如需查看 Compose 中有趣的动画的更多示例,请查看以下内容: