我有一个矢量可绘制的图像,通过painter属性设置为Image的源。现在我想要更改源,但同时也要动画更改。所谓的动画效果并不是指使用路径数据进行变形动画,而是希望具有简单的淡入淡出效果。因此,一旦更改了源,我希望隐藏以前的图像,并显示当前的可绘制图像,并具有淡入淡出动画。
现在我正在使用一种解决方法,我使用了两个不同图像的源,并使用AnimatedVisibility来更改图像的可见性以匹配主题。是否有标准的方式可以动画更改源?这是我使用的hack,但我认为非常丑陋。@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
)
}
}
AnimatedContent
的targetState
值自上次重新组合以来发生了更改,则将启动@Jerome动画。您可以以多种方式在视图模型中存储状态 - 组成可变状态,Flow
或LiveData
- 任何会在值更改时引起重新组合的东西。 - Phil Dukhov