Compose 中的动画快速指南

Compose 有许多内置动画机制,知道选择哪一个可能会让人不知所措。下面列出了常见的动画用例。有关可用不同 API 选项的完整详细信息,请阅读完整的Compose 动画文档

动画化常见的可组合项属性

Compose 提供了便捷的 API,可帮助您解决许多常见的动画用例。本节演示了如何动画化可组合项的常见属性。

动画化出现/消失

Green composable showing and hiding itself
图 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 最终会从组合中移除该项目。

Animating the alpha of a composable
图 2. 动画化可组合项的 alpha 值

动画化背景颜色

Composable with background color changing over time as an animation, where the colors are fading into one another.
图 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() 对于一次性颜色设置是可以接受的,但在随时间动画化颜色时,这可能会导致不必要的重组。

有关无限动画化背景颜色,请参阅重复动画部分

动画化可组合项的大小

Green composable animating its size change smoothly.
图 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 来描述大小更改应如何发生。

动画化可组合项的位置

Green composable smoothly animating down and to the right
图 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 boxes with the 2nd box animating its X,Y position, the third box responding by moving itself by Y amount too.
图 6. 使用 Modifier.layout{ } 进行动画

动画化可组合项的内边距

Green composable getting smaller and bigger on click, with padding being animated
图 7. 可组合项的内边距正在动画化

要动画化可组合项的内边距,请使用 animateDpAsState 结合 Modifier.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. 可组合项的海拔在点击时进行动画处理

要动画化可组合项的海拔,请使用 animateDpAsState 结合 Modifier.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 composable saying
图 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)
    )
}

动画化文本颜色

The words
图 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
    },
    // ...
)

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

Green screen saying
图 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博客文章

在导航到不同目标时进行动画处理

Two composables, one green saying Landing and one blue saying Detail, animating by sliding the detail composable over the landing composable.
图 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(
            // ...
        )
    }
}

有许多不同种类的进入和退出过渡,它们对传入和传出的内容应用不同的效果,有关更多信息,请参阅文档

重复动画

A green background that transforms into a blue background, infinitely by animating between the two colors.
图 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
    }
)

创建顺序动画

Four circles with green arrows animating between each one, animating one by one after one another.
图 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))
}

创建并发动画

Three circles with green arrows animating to each one, animating all together at the same time.
图 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(**之间**的缩写):基于持续时间的动画,通过 Easing 函数在两个值之间进行动画处理。
  • keyframes:用于在动画中指定特定关键点值的规范。
  • repeatable:基于持续时间的规范,运行一定次数,由 RepeatMode 指定。
  • infiniteRepeatable:基于持续时间的规范,永远运行。
  • snap:立即捕捉到最终值,没有任何动画。
Write your alt text here
图 16. 未设置规范与设置自定义弹簧规范

阅读完整文档以获取有关 animationSpecs 的更多信息。

其他资源

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