如何使 Jetpack Compose Image 无限动画

Sol*_*vek 2 animation android-jetpack-compose

我有一个animated-vector可绘制的。我希望这个动画矢量在显示该图像时循环动画。对此找不到好的解决方案。

        val image = animatedVectorResource(R.drawable.no_devices_animated)
        var atEnd by remember { mutableStateOf(false) }
        Image(
            painter = image.painterFor(atEnd),
            "image",
            Modifier.width(150.dp).clickable {
                atEnd = !atEnd
            },
            contentScale = ContentScale.Fit)
Run Code Online (Sandbox Code Playgroud)

当我点击图像时,它会产生动画,但随后停止。这是一种无限的进步。

ngl*_*ber 6

将我的解决方案留在这里(使用 compose 1.2.0-alpha07)。

添加依赖项到你的build.gradle

dependencies {
    implementation "androidx.compose.animation:animation:$compose_version"
    implementation "androidx.compose.animation:animation-graphics:$compose_version"
}
Run Code Online (Sandbox Code Playgroud)

并执行以下操作:

dependencies {
    implementation "androidx.compose.animation:animation:$compose_version"
    implementation "androidx.compose.animation:animation-graphics:$compose_version"
}
Run Code Online (Sandbox Code Playgroud)

如果您需要从头开始重复动画,我发现的唯一方法是创建两个矢量可绘制对象,例如ic_start使用ic_end动画矢量可绘制对象中声明的信息,然后执行以下操作:

@ExperimentalAnimationGraphicsApi
@Composable
fun AnimatedVectorDrawableAnim() {
    val image = AnimatedImageVector.animatedVectorResource(R.drawable.avd_anim)
    var atEnd by remember { mutableStateOf(false) }
    // This state is necessary to control start/stop animation
    var isRunning by remember { mutableStateOf(true) }
    // The coroutine scope is necessary to launch the coroutine 
    // in response to the click event
    val scope = rememberCoroutineScope()
    // This function is called when the component is first launched
    // and lately when the button is pressed
    suspend fun runAnimation() {
        while (isRunning) {
            delay(1000) // set here your delay between animations
            atEnd = !atEnd
        }
    }
    // This is necessary just if you want to run the animation when the
    // component is displayed. Otherwise, you can remove it.
    LaunchedEffect(image) {
        runAnimation()
    }
    Image(
        painter = rememberAnimatedVectorPainter(image, atEnd),
        null,
        Modifier
            .size(150.dp)
            .clickable {
                isRunning = !isRunning // start/stop animation
                if (isRunning) // run the animation if isRunning is true.
                    scope.launch {
                        runAnimation()
                    }
            },
        contentScale = ContentScale.Fit,
        colorFilter = ColorFilter.tint(Color.Red)
    )
}
Run Code Online (Sandbox Code Playgroud)

因此,当动画矢量位于结束位置时,将绘制静态图像。延迟后,再次播放动画。如果需要连续重复,请将延迟设置为与动画相同的持续时间。

结果如下: 在此输入图像描述