清晰的画布绘图:Jetpack Compose

时间:2021-05-03 19:51:03

标签: android canvas android-jetpack-compose

在画布上完成绘图后,如下所示:

@Composable
fun DrawFigures(count: Int){
    val radius = 200f
    val animateFloat = remember { Animatable(0f) }
    if(count == 1)
        LaunchedEffect(animateFloat) {
            animateFloat.animateTo(
                targetValue = 1f,
                animationSpec = tween(durationMillis = 3000, easing = LinearEasing))
        }

   Canvas(modifier = Modifier.fillMaxSize()){
       drawArc(
           color = Color.Black,
           startAngle = 0f,
           sweepAngle = 360f * animateFloat.value,
           useCenter = false,
           topLeft = Offset(size.width / 4, size.height / 4),
           size = Size(radius * 2 ,
               radius * 2),
           style = Stroke(2.0f))

    //Other drawings
    drawLine(..)
    drawLine(..)
   }
}

此动画绘制圆形。但是重新组合后无论计数值是多少,始终显示圆圈。我们如何清除画布或有其他方法可以根据计数值实现此动画?

编辑:还有其他需要绘制的图形,调用该组合并根据计数值进行重新组合。这是一个游戏,当用户再次点击播放时,计数值将为零。

1 个答案:

答案 0 :(得分:1)

如果要清除 Canvas 元素,请使用状态提升技术。

@Composable
fun DrawFigures(count: Int){
    val radius = 200f
    val animateFloat = remember { Animatable(0f) }
    ...
    if(animateFloat.isRunning){ // The Canvas will disappear if the Animator is completed. Also, it won't appear when the Animator hasn't started yet
        Canvas(modifier = Modifier.fillMaxSize()){
            ...
        }
    }
}

这里的结果:

Result image

查看更多:State in Compose