Compose 中的动画矢量图像

您可以通过几种不同的方式在 Compose 中为矢量添加动画效果。您可以使用以下任意一种方式:

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

带动画的矢量可绘制对象(实验性)

沙漏以动画形式呈现其内容并旋转
图 1. Compose 中的动画矢量可绘制对象

如需使用 AnimatedVectorDrawable 资源,请使用 animatedVectorResource 加载可绘制对象文件,并传入 boolean 以在可绘制对象的开始和结束状态之间切换,从而执行动画。

@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
    )
}

如需详细了解可绘制文件的格式,请参阅为可绘制图形添加动画