【问题标题】:Jetpack Compose Animation skips to target value immediatelyJetpack Compose Animation 立即跳到目标值
【发布时间】:2023-01-19 23:04:00
【问题描述】:

我正在尝试实现一个简单的圆形计时器的流畅动画。像这样,但更流畅

然而,它只是立即跳到 targetValue,就是这样,根本没有动画。我正在尝试这样做:

@Composable
private fun SampleTimer(duration: Int, modifier: Modifier = Modifier) {
    var animatedPercentage by remember { mutableStateOf(1f) }
    LaunchedEffect(Unit) {
        animate(
            initialValue = 1f,
            targetValue = 0f,
            animationSpec = infiniteRepeatable(
                tween(
                    durationMillis = duration.seconds.inWholeMilliseconds.toInt(),
                    easing = LinearEasing,
                ),
            ),
        ) { value, _ ->
            animatedPercentage = value
        }
    }
    val arcColor = MaterialTheme.colors.primaryVariant
    Canvas(
        modifier = modifier,
    ) {
        drawArc(
            color = arcColor,
            useCenter = true,
            startAngle = -90f,
            sweepAngle = -360f * animatedPercentage,
        )
    }
}

为什么会这样,我在这里错过了什么?

【问题讨论】:

    标签: android kotlin android-jetpack-compose jetbrains-compose android-jetpack-compose-canvas


    【解决方案1】:

    您可以使用 Animatable 状态。角度将从 0–360° 动画。

    就像是:

    val angle = remember {
        Animatable(0f)
    }
    LaunchedEffect(angle) {
        launch {
            angle.animateTo(360f, animationSpec =
                 infiniteRepeatable(
                    tween(
                        durationMillis = 5000,
                        easing = LinearEasing,
                    ),
                )
            )
        }
    }
    
    val arcColor = Red
    
    Canvas(
        modifier = Modifier.size(100.dp),
    ) {
        drawArc(
            color = arcColor,
            useCenter = true,
            startAngle = -90f,
            sweepAngle = -angle.value,
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-15
      • 2020-04-29
      • 2022-06-19
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      • 2023-01-22
      • 1970-01-01
      相关资源
      最近更新 更多