'Android Jetpack Compose (Composable) Change Image source with animation

I have a vector drawable set as source via the painter attribute to an Image. Now I want to change the source, but also animate the change. By animation I don`t mean morphing animation with the path data, rather I want to have simple FadeIn, FadeOut effects. So once the source is changed I want the to hide the previous and show the current drawable with fade animation.

enter image description here

Now I am doing a workaround, I am using 2 Images with the sources of the two different images, and using AnimatedVisibility to change the visibility of the images, to match the theme. Is there a standard way of changing the source with animation?

Here is the hack I use, which is very ugly in my opinion

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source