代码逻辑:
@Composable
fun ShowLoading() {
val rotation = remember { Animatable(0f) }
// 开启旋转动画
LaunchedEffect(isRotating) {
launch {
rotation.animateTo(
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 5000,
easing = LinearEasing
),
repeatMode = RepeatMode.Restart
)
)
}
}
// 旋转的图片 - rotate(rotation.value)
Image(
painter = painterResource(id = R.mipmap.xxx),
contentDescription = null,
modifier = Modifier.wrapContentSize().padding(15.dp).rotate(rotation.value)
)
}
代码详细解释:
val rotation = remember { Animatable(0f) }:
-
这行代码使用
remember初始化一个Animatable对象,并设置初始值为0f。 -
Animatable用于表示一个可以随时间变化的动画值。 -
remember函数确保该状态在重新组合(recomposition)时得以保留。
LaunchedEffect(isRotating):
-
LaunchedEffect是一个用于管理副作用的 Compose API,它会在isRotating状态发生变化时执行其中的代码块。 -
isRotating是一个触发动画的条件变量(虽然在代码中没有定义它,假设是由外部传入或控制的状态)。
launch块:
-
在
LaunchedEffect中使用launch启动一个协程,以异步方式执行旋转动画。 -
rotation.animateTo是动画的核心,设置了目标值为360f,即图片将旋转 360 度。 -
animationSpec是动画的规格,这里使用了infiniteRepeatable,表示动画将无限循环。 -
tween定义了动画的持续时间为 5000 毫秒(即5秒),并使用LinearEasing使动画匀速进行。 -
repeatMode = RepeatMode.Restart表示动画在每次循环时从头开始。
Image组件:
-
Image用于显示图片。它通过painterResource加载资源 ID 为R.mipmap.xxx的图片。 -
modifier是 Compose 中用于修饰 UI 元件的属性,这里通过Modifier组合了一些修饰符:-
wrapContentSize()使图片保持其原始大小。 -
padding(15.dp)添加15dp的内边距。 -
rotate(rotation.value)将图片按当前的旋转值进行旋转,rotation.value是动画过程中不断变化的值。
-