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

如何用Jetpack Compose实现iOS风格旋转动画

Jetpack Compose实现iOS风格旋转动画

核心实现思路

iOS风格的旋转动画通常是无限循环的平滑匀速旋转,我们可以借助Jetpack Compose的动画API结合rotate修饰符实现,通过动画规范控制循环逻辑与运动曲线。

完整代码示例

import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

@Composable
fun IOStyleRotatingIcon() {
    // 控制动画启停的状态
    var isRotating by remember { mutableStateOf(false) }
    
    // 绑定旋转角度的动画状态,无限循环完成360度旋转
    val rotationAngle by animateFloatAsState(
        targetValue = if (isRotating) 360f else 0f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 1000, easing = androidx.compose.animation.core.LinearEasing),
            repeatMode = RepeatMode.Restart
        ),
        finishedListener = {
            if (!isRotating) isRotating = false
        }
    )

    // 页面加载时自动启动动画(可根据业务调整触发时机)
    LaunchedEffect(Unit) {
        isRotating = true
    }

    // 示例:展示旋转的图标(替换为你的资源)
    Image(
        painter = painterResource(id = R.drawable.ic_refresh),
        contentDescription = "Rotating icon",
        modifier = Modifier
            .size(48.dp)
            .rotate(rotationAngle)
    )
}

关键细节说明

  • 无限循环逻辑:infiniteRepeatable让动画持续循环,RepeatMode.Restart确保每次循环从0度重新开始旋转。
  • 动画曲线适配:LinearEasing实现匀速旋转,贴合iOS原生加载动画的平滑特性;若需缓动效果,可替换为FastOutSlowInEasing等其他曲线。
  • 灵活启停控制:isRotating状态可绑定到按钮点击、数据加载状态等事件,实现动画的暂停/恢复。

扩展调整(单次旋转场景)

如果需要实现点击后旋转一圈的单次动画,可修改动画规范并移除循环配置:

animationSpec = tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing)

同时在动画完成后重置角度状态即可。

内容的提问来源于stack exchange,提问作者Eight 8

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:20:00