Ejemplo práctico 6: Animación con graphicsLayer y Scaffold
Objetivo
Este ejemplo se creará un Scaffold
con TopAppBar
y FloatingActionButton
. Se creará un composable que anime su rotación y escala usando graphicsLayer
y un botón flotante que inicie o detenga la animación.
Composable EjemploAvanzadoGraphicsLayer
1@OptIn(ExperimentalMaterial3Api::class)
2@Composable
3fun EjemploAvanzadoGraphicsLayer() {
4 var animar by remember { mutableStateOf(false) }
5 val rotacion by animateFloatAsState(
6 targetValue = if (animar) 360f else 0f,
7 animationSpec = tween(durationMillis = 2000, easing = LinearEasing)
8 )
9 val escala by animateFloatAsState(
10 targetValue = if (animar) 1.5f else 1f,
11 animationSpec = tween(durationMillis = 2000, easing = LinearEasing)
12 )
13
14 Scaffold(
15 topBar = {
16 TopAppBar(title = { Text("GraphicsLayer Avanzado") })
17 },
18 floatingActionButton = {
19 FloatingActionButton(onClick = { animar = !animar }) {
20 Icon(Icons.Default.PlayArrow, contentDescription = "Animar")
21 }
22 }
23 ) { padding ->
24 Box(
25 modifier = Modifier
26 .fillMaxSize()
27 .padding(padding),
28 contentAlignment = Alignment.Center
29 ) {
30 Box(
31 modifier = Modifier
32 .size(150.dp)
33 .graphicsLayer(
34 rotationZ = rotacion,
35 scaleX = escala,
36 scaleY = escala,
37 alpha = 0.8f,
38 shadowElevation = 16f
39 )
40 .background(Color(0xFF6200EE)),
41 contentAlignment = Alignment.Center
42 ) {
43 Text("Animado", color = Color.White, fontSize = 18.sp)
44 }
45 }
46 }
47}
Para visualizar el ejemplo en la vista previa de Android Studio añade el siguiente método:
1@Preview(showBackground = true)
2@Composable
3fun VistaPreviaEjemploAvanzado() {
4 EjemploAvanzadoGraphicsLayer()
5}
En resumen, se coloca un Scaffold
con barra superior y un FAB, se crea un Box
central ocupando toda la pantalla que rota 360 grados y se escala a 1.5x cuando se pulsa el FAB. El estado animar
controla si se inicia o detiene la animación. Por último, se utiliza animateFloatAsState
para interpolar suavemente.