你如何制作图像交换的动画

How do you animate a swap of Image

我想为 Icons.Default.CheckIcons.Default.Close 之间的变化制作动画,制作淡入淡出和淡入淡出的动画。

我已经研究了 animation*AsState 但是似乎没有内置的方法可以开箱即用,而且我对 Jetpack Compose 的经验不足,无法找出正确的方法制作这样的自定义动画的方法。

if(isChecked){
    Icon(imageVector = Icons.Default.Check, contentDescription = "", tint = Color.Black)
}else{
    Icon(imageVector = Icons.Default.Close, contentDescription = "", tint = Color.Gray)
}

你可以使用副作用

@Composable
fun Fader(trigger: Boolean){ // trigger is a delegated MutableState variable. 

 var alpha = 1f
 var animatedAlpha by animateFloatAsState(targetValue = alpha)

 LaunchedEffect(key = trigger){
  //Triggered upon key change. Change the value of trigger upon a button click or similar event.
  alpha = 0f // First we make it go all the way down
  delay(500) // Slight Delay, as a pause
  alpha = 1f // Bring it up
 }

 // Now, when the trigger is set, a recomposition should occur.
 // So, we change set the value here normally since the side-effect is taking care
 // of the animation

 Icon(
  imageVector = if(triggered) .. else .., //Add your Vectors here
  contentDescription = "Bla Bla Bla",
  alpha = animatedAlpha
 )

 //Done
}

您可以使用 Crossfade,如 animation documentation 所示。

Crossfade(targetState = isChecked) { isChecked ->
    // note that it's required to use the value passed by Crossfade
    // instead of your state value
    if (isChecked) {
        Icon(imageVector = Icons.Default.Check, contentDescription = "", tint = Color.Black)
    } else {
        Icon(imageVector = Icons.Default.Close, contentDescription = "", tint = Color.Gray)
    }
}