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 是动画过程中不断变化的值。

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值