Android Jetpack Compose (Composable) 用动画改变图像源

标签 android android-animation android-jetpack-compose

我通过图像的画家属性将矢量可绘制集设置为源。现在我要更改源,还要为更改设置动画。动画我不是指用路径数据变形动画,而是我想要简单的淡入淡出效果。因此,一旦更改了源,我希望隐藏上一个并显示带有淡入淡出动画的当前可绘制对象。
enter image description here
现在我正在做一个解决方法,我使用 2 个图像和两个不同图像的来源,并使用 AnimatedVisibility更改图像的可见性,以匹配主题。有没有用动画改变源的标准方法?
这是我使用的黑客,在我看来这很丑陋

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun AnimatedImage(modifier: Modifier, isLightTheme: Boolean, srcLight: Int = R.drawable.ic_sun, srcDark: Int = R.drawable.ic_moon) {

    val colors = LocalColors.current
    val (enter, exit) = remember {
        arrayListOf(
            fadeIn(animationSpec = tween(durationMillis = 1500)),
            fadeOut(animationSpec = tween(durationMillis = 500))
        )
    }

    AnimatedVisibility(
        visible = !isLightTheme,
        enter = enter as EnterTransition,
        exit = exit as ExitTransition
    ) {
        Image(
            painter = painterResource(id = srcDark), contentDescription = "",
            colorFilter = ColorFilter.tint(colors.secondsArrow),
            modifier = modifier
        )
    }

    AnimatedVisibility(
        visible = isLightTheme,
        enter = enter,
        exit = exit
    ) {
        Image(
            painter = painterResource(id = srcLight), contentDescription = "",
            colorFilter = ColorFilter.tint(colors.secondsArrow),
            modifier = modifier
        )
    }
}

最佳答案

您可以使用基本 Crossfade动画:

Crossfade(
    flag,
    animationSpec = tween(1000)
) { targetState ->
    Image(
        painterResource(if (targetState) R.drawable.ic_redo else R.drawable.ic_undo),
        contentDescription = null,
        modifier = Modifier.background(Color.Black)
    )
}
或者如果您需要更复杂的,可以使用 AnimatedContent - 我的例子相当于你的双 - AnimatedVisibility :
AnimatedContent(
    flag,
    transitionSpec = {
        fadeIn(animationSpec = tween(durationMillis = 1500)) with
                fadeOut(animationSpec = tween(durationMillis = 500))
    }
) { targetState ->
    Image(
        painterResource(if (targetState) R.drawable.ic_redo else R.drawable.ic_undo),
        contentDescription = null,
        modifier = Modifier.background(Color.Black)
    )
}
请注意,在这两种情况下都需要使用 targetState传入内容 lambda,因为此 lambda 在转换期间被多次重组。
您可以在 Compose Animation documentation 中找到更多信息

关于Android Jetpack Compose (Composable) 用动画改变图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70956195/

相关文章:

android - 检测 Jetpack Compose 中的用户事件是否为按下或双击

java - 无法运行android测试套件: Exception in thread "main" java. lang.ClassNotFoundException

java - mediaPlayer CompletionListener 在完成歌曲之前播放下一首歌曲

java - 为什么我的 fragment 是空白的?

android - android屏幕坐标如何工作?

java - 使用 android fragment 动画共享元素转换似乎是一场噩梦

android - 在 Robolectric 3.0+ 中跳过动画

android - 我可以删除旧的 Android SDK 构建工具包吗?

android - 底部导航不与底部对齐

android - 可组合项因传递的回调过多而变得臃肿