Compose 中的动画矢量图

在 Compose 中为矢量设置动画有几种不同的方法。您可以使用以下任一方式:

  • AnimatedVectorDrawable 文件格式
  • ImageVector 与 Compose 动画 API 结合使用,如这篇 Medium 文章
  • 第三方解决方案,例如 Lottie

动画矢量 Drawable(实验性)

Hourglass animating its contents and rotating
图 1. Compose 中的动画矢量 drawable

要使用 AnimatedVectorDrawable 资源,请使用 animatedVectorResource 加载 drawable 文件,并传入一个 boolean 值以在 drawable 的开始和结束状态之间切换,从而执行动画。

@Composable
fun AnimatedVectorDrawable() {
    val image = AnimatedImageVector.animatedVectorResource(R.drawable.ic_hourglass_animated)
    var atEnd by remember { mutableStateOf(false) }
    Image(
        painter = rememberAnimatedVectorPainter(image, atEnd),
        contentDescription = "Timer",
        modifier = Modifier.clickable {
            atEnd = !atEnd
        },
        contentScale = ContentScale.Crop
    )
}

如需详细了解 drawable 文件的格式,请参阅动画化 drawable 图形