Infinite Animation Recomposition

  Kiến thức lập trình

So I have a background that consist of 3 random movinig circles, that are radial gradients
these circle will be moving across the screen in a random pattern and infinite.

@Composable
fun AuroraView(startAnimation: Boolean) {
  val scope = rememberCoroutineScope()
  val displayMetrics = LocalContext.current.resources.displayMetrics
  val animationDelay = 4
  val animationDuration = 8
  val animationSpec = tween<Offset>(animationDuration * 1000, easing = FastOutSlowInEasing)
  var circlePositions by remember {
    mutableStateOf(
        listOf(
            Offset.Zero,
            Offset(displayMetrics.widthPixels.toFloat(), 0f),
            Offset(displayMetrics.widthPixels.toFloat(), displayMetrics.heightPixels.toFloat())
        )
    )
  }

  val auroraColors = listOf(
    "#8B8BCB",
    "#F8906F",
    "#FADDF8"
  )

  val animatedOffsets = circlePositions.mapIndexed { index, _ ->
    animateOffsetAsState(
        targetValue = circlePositions[index],
        animationSpec = animationSpec,
        label = "offset${index + 1}"
    )
  }

  LaunchedEffect(startAnimation){
    scope.launch(IO) {
        delay(animationDelay.seconds)
        while (startAnimation) {
            circlePositions = circlePositions.map {
                Offset(
                    getRandomPosition(displayMetrics.widthPixels),
                    getRandomPosition(displayMetrics.heightPixels)
                )
            }
            delay(animationDuration.seconds)
        }
    }
  }

  Canvas(modifier = Modifier.fillMaxSize()) {
    auroraColors.forEachIndexed { index, color ->
        drawRect(
            brush = Brush.radialGradient(
                colors = listOf(
                    Color(android.graphics.Color.parseColor(color)),
                    Color.Transparent
                ),
                center = animatedOffsets[index].value,
                radius = 1000F,
            ),
            size = size
        )
    }
  }
}

But I’m getting a recomposition every animationDuration,
is there a way to improve this? or It will be recomposing everytime no matter what?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT