Tengo una pantalla con una Imagen en una esquina de la pantalla y quiero animarla al centro de la pantalla. Algo así como pasar de
Icon( painter = //, contentDescription = //, modifier = Modifier.size(36.dp) )para
Icon( painter = //, contentDescription = //, modifier = Modifier.fillMaxSize() )El primero se coloca en la esquina superior izquierda de la pantalla y el segundo en el centro. ¿Cómo puedo animar entre los dos estados?
Prueba este:
@Composable fun DUM_E_MARK_II(triggered: Boolean) { BoxWithConstraints { val size by animateDpAsState(if (triggered) 36.dp else maxHeight) Icon( imageVector = Icons.Filled.Warning, contentDescription = "Just a better solution to the problem", modifier = Modifier.size(size) ) } }
Para que las animaciones funcionen en Compose, debe animar un valor de algún modificador en particular. No hay forma de animar entre diferentes conjuntos de modificadores.
Siguiendo este párrafo de documentación, puede animar el valor de Modifier.size .
Primero espero a que se determine el tamaño de la imagen, con este valor se puede configurar el modificador de size ( then uso con un Modifier vacío antes de eso) y luego se puede animar este valor.
Aquí hay una muestra:
Column { val animatableSize = remember { Animatable(Size.Zero, Size.VectorConverter) } val (containerSize, setContainerSize) = remember { mutableStateOf<Size?>(null) } val (imageSize, setImageSize) = remember { mutableStateOf<Size?>(null) } val density = LocalDensity.current val scope = rememberCoroutineScope() Button(onClick = { scope.launch { if (imageSize == null || containerSize == null) return@launch val targetSize = if (animatableSize.value == imageSize) containerSize else imageSize animatableSize.animateTo( targetSize, animationSpec = tween(durationMillis = 1000) ) } }) { Text("Animate") } Box( Modifier .padding(20.dp) .size(300.dp) .background(Color.LightGray) .onSizeChanged { size -> setContainerSize(size.toSize()) } ) { Image( Icons.Default.Person, contentDescription = null, modifier = Modifier .then( if (animatableSize.value != Size.Zero) { animatableSize.value.run { Modifier.size( width = with(density) { width.toDp() }, height = with(density) { height.toDp() }, ) } } else { Modifier } ) .onSizeChanged { intSize -> if (imageSize != null) return@onSizeChanged val size = intSize.toSize() setImageSize(size) scope.launch { animatableSize.snapTo(size) } } ) } }Resultado:
