使用暂停/恢复功能制作自定义进度动画

huangapple go评论88阅读模式
英文:

Compose Custom Progress Animation With Pause/Resume

问题

我想制作一个带有暂停和播放功能的进度条,就像这样。

使用暂停/恢复功能制作自定义进度动画

如何使用Compose获得这种效果?

我尝试了很多动画,但无法处理开始/停止操作。有什么最优雅的方法可以做到这一点?

英文:

I want to make a progress bar with pause and play, like this.

使用暂停/恢复功能制作自定义进度动画

How can I got this output with compose ?

I tried a lot of animations but couldn't handle with the start/stop operations. What is the most elegant way to do this?

答案1

得分: 1

这是我认为最简单的方法:

val progress by remember { mutableStateOf(0f) }
val animatedProgress by animateFloatAsState(targetValue = progress,
    animationSpec = tween(
        durationMillis = 1000,
        easing = LinearEasing
    ))
val paused by remember { mutableStateOf(false) }

LaunchedEffect(paused) {
    if (!paused) while (progress < 1f) {
        progress += 0.1f // 或者其他步进值
        delay(1000)  // 或者其他延迟值
    }
}

在这里甚至不需要使用动画,你可以直接将 progress 的值应用为组件的尺寸分数。

animatedProgress 会动画到目标值,这在这个解决方案中是“可暂停的”。因此,当目标值不变时,动画会停止。

英文:

The easiest way is this one I think:

val progress by remember { mutableStateOf(0f) }
val animatedProgress by animateFloatAsState(targetValue = progress,
    animationSpec = tween(
        durationMillis = 1000,        
        easing = LinearEasing
    ))
val paused by remember { mutableStateOf(false) }

LaunchedEffect(paused) {
    if (!paused) while (progress &lt; 1f) {
        progress += 0.1f //or another step
        delay(1000)  //or another delay
    }
}

Here it is not even necessary to use animation, you can directly apply the progress value as a component's size fraction.

animatedProgress animates to target value, which is "pausable" in this solution. So when the target value doesn't change, the animation stops

huangapple
  • 本文由 发表于 2023年3月3日 20:49:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定