You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中如何实现Composable旋转动画并监听进度切换图片

实现方案

你可以通过Compose的Animatable动画API配合状态监听实现需求,完整实现代码如下:

@Composable
fun MyImage(displayImage: Painter) {
    // 持有当前实际渲染的图片,避免入参变更时直接替换
    var currentDisplayPainter by remember { mutableStateOf(displayImage) }
    // 控制旋转角度的动画实例
    val rotationAnimatable = remember { Animatable(0f) }

    // 监听入参displayImage变更,触发旋转动画
    LaunchedEffect(displayImage) {
        // 动画启动前重置旋转角度为初始值
        rotationAnimatable.snapTo(0f)
        // 执行360度旋转动画,可调整durationMillis参数自定义动画时长
        rotationAnimatable.animateTo(
            targetValue = 360f,
            animationSpec = tween(durationMillis = 600)
        )
    }

    // 监听旋转角度,到达180度时切换为新图片
    LaunchedEffect(rotationAnimatable.value) {
        if (rotationAnimatable.value >= 180f && currentDisplayPainter != displayImage) {
            currentDisplayPainter = displayImage
        }
    }

    Image(
        painter = currentDisplayPainter,
        contentDescription = null,
        modifier = Modifier
            .size(36.dp)
            .clip(CircleShape)
            .rotate(rotationAnimatable.value) // 给Image应用旋转属性
    )
}

逻辑说明

  • 我们没有直接把入参displayImage传给Image组件,而是额外声明了currentDisplayPainter状态来控制实际渲染的图片,避免入参变更时直接触发图片替换
  • 用LaunchedEffect监听displayImage的变化,每次入参更新就启动一次360度旋转动画
  • 监听旋转角度的变化,当角度首次达到/超过180度时,把实际渲染的图片替换为新的入参值,后续动画继续旋转剩余180度,完成整个切换效果

内容的提问来源于stack exchange,提问作者Arpit Shukla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:45:02