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)时得以保留。

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

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

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

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

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

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

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

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

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

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

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

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

相关推荐
AFinalStone2 小时前
Android 7系统异常问题排查(四)Framework层(上)—System Server Watchdog
android·系统异常
zzzll11112 小时前
Claude Code离线安装方案揭秘
开发语言·php
mifengxing3 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
wling03013 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
郝学胜-神的一滴3 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
宝杰X74 小时前
Android Room3 多平台数据库
android·数据库
xrandzj4 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
ZacJi4 小时前
当苹果将系统 API 划归 @MainActor:一次跨 SDK 版本的 Swift 并发踩坑与破局实战
ios·swift
DLYSB_5 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
mardelan5 小时前
2026年iOS短视频总结工具测评强识别提效率 整理清晰更省心
ios·音视频