欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > Kotlin compose 实现Image 匀速旋转

Kotlin compose 实现Image 匀速旋转

2025/2/26 6:36:22 来源:https://blog.csdn.net/qq_27247815/article/details/141034782  浏览:    关键词:Kotlin compose 实现Image 匀速旋转

代码逻辑:


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

代码详细解释:

1. val rotation = remember { Animatable(0f) }:

  • 这行代码使用 remember 初始化一个 Animatable 对象,并设置初始值为 0f

  • Animatable 用于表示一个可以随时间变化的动画值。

  • remember 函数确保该状态在重新组合(recomposition)时得以保留。

2. LaunchedEffect(isRotating):

  • LaunchedEffect 是一个用于管理副作用的 Compose API,它会在 isRotating 状态发生变化时执行其中的代码块。

  • isRotating 是一个触发动画的条件变量(虽然在代码中没有定义它,假设是由外部传入或控制的状态)。

3. launch 块:

  • 在 LaunchedEffect 中使用 launch 启动一个协程,以异步方式执行旋转动画。

  • rotation.animateTo 是动画的核心,设置了目标值为 360f,即图片将旋转 360 度。

  • animationSpec 是动画的规格,这里使用了 infiniteRepeatable,表示动画将无限循环。

  • tween 定义了动画的持续时间为 5000 毫秒(即5秒),并使用 LinearEasing 使动画匀速进行。

  • repeatMode = RepeatMode.Restart 表示动画在每次循环时从头开始。

4. Image 组件:

  • Image 用于显示图片。它通过 painterResource 加载资源 ID 为 R.mipmap.xxx 的图片。

  • modifier 是 Compose 中用于修饰 UI 元件的属性,这里通过 Modifier 组合了一些修饰符:

    • wrapContentSize() 使图片保持其原始大小。

    • padding(15.dp) 添加15dp的内边距。

    • rotate(rotation.value) 将图片按当前的旋转值进行旋转,rotation.value 是动画过程中不断变化的值。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词