如何使用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
相关产品推荐
相关产品推荐

