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

如何使用Jetpack Compose实现旋转活动指示器?

如何用Jetpack Compose实现旋转活动指示器

旋转活动指示器效果

下面提供两种实用的实现方案,满足不同场景需求:

方案一:内置动画组件快速实现

利用Compose的AnimatedRotation组件,几行代码就能实现基础旋转效果:

@Composable
fun RotatingIconIndicator() {
    AnimatedRotation(
        degrees = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 1000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    ) {
        Icon(
            imageVector = Icons.Default.Refresh,
            contentDescription = "旋转加载指示器",
            tint = Color.DarkGray,
            modifier = Modifier.size(48.dp)
        )
    }
}

方案二:自定义Canvas绘制旋转指示器

如果需要更个性化的样式(比如环形进度式旋转),可以结合Canvas与动画API实现:

@Composable
fun CustomRotatingRingIndicator() {
    // 驱动旋转的动画值
    val rotationAngle by animateFloatAsState(
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(1200, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        ),
        label = "ringRotation"
    )

    Canvas(modifier = Modifier.size(48.dp)) {
        val center = Offset(size.width / 2, size.height / 2)
        val ringRadius = size.minDimension / 2 * 0.75f
        val strokeWidth = 4.dp.toPx()

        // 绘制灰色背景环
        drawCircle(
            color = Color.LightGray,
            center = center,
            radius = ringRadius,
            style = Stroke(width = strokeWidth)
        )

        // 绘制旋转的高亮弧段
        drawArc(
            color = Color(0xFF2196F3),
            startAngle = rotationAngle - 90, // 从顶部起始
            sweepAngle = 90f,
            useCenter = false,
            topLeft = Offset(center.x - ringRadius, center.y - ringRadius),
            size = Size(ringRadius * 2, ringRadius * 2),
            style = Stroke(width = strokeWidth, cap = StrokeCap.Round)
        )
    }
}

关键参数说明

  • 修改tween的durationMillis可以调整旋转速度:数值越小,转速越快
  • 自定义Canvas方案中,可通过修改strokeWidth、color、sweepAngle等参数,打造不同视觉风格的指示器
  • 两种方案均通过infiniteRepeatable实现无限循环旋转

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:15:30