[英]Android Jetpack Compose (Composable) Change Image source with animation
我通过图像的画家属性将矢量可绘制集设置为源。 现在我要更改源,还要为更改设置动画。 animation 我不是指用路径数据变形 animation,而是我想要简单的淡入淡出效果。 因此,一旦更改了源,我希望隐藏前一个并使用淡入淡出 animation 显示当前可绘制对象。
现在我正在做一个解决方法,我使用 2 个图像和两个不同图像的来源,并使用AnimatedVisibility来更改图像的可见性,以匹配主题。 是否有使用 animation 更改源的标准方法?
这是我使用的黑客,在我看来这很丑陋
@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
animation:
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)
)
}
请注意,在这两种情况下,都需要使用在内容 lambda 中传递的targetState
,因为此 lambda 在转换期间会多次重组。
您可以在撰写 Animation文档中找到更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.