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 的进入和退出参数可让您配置可组合项在显示和消失时的行为方式。如需了解详情,请阅读完整 文档

为可组合项的可见性添加动画效果的另一种方法是使用 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)
    )
}

2 个盒子,其中第 2 个盒子在 X、Y 位置上进行动画处理,第 3 个盒子通过将自身移动 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 可组合项,并为每个状态设置不同的海拔高度属性值。

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

Text 可组合项,内容为
图 9.文本在两种大小之间平稳地添加动画效果

为文本的缩放、平移或旋转添加动画效果时,请将 textMotion 参数设置为 TextStyleTextMotion.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 可指定动画应如何来回播放。

使用 repeatable 可重复播放指定次数。

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:基于物理的动画,是所有动画的默认设置。您可以更改 stiffness 或 dampingRatio 以实现不同的动画外观和感觉。
  • tweenbetween 的缩写):基于时长的动画,使用 Easing 函数在两个值之间添加动画效果。
  • keyframes:用于在动画中的特定关键点指定值的规范。
  • repeatable:基于时长的规范,运行指定次数,由 RepeatMode 指定。
  • infiniteRepeatable:基于时长的规范,无限期运行。
  • snap:立即捕捉到结束值,没有任何动画效果。
在此处输入替代文本
图 16.未设置规范与自定义弹簧规范集

如需详细了解 animationSpec,请阅读完整文档。

其他资源

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