Infinite rotation of an Image in Jetpack Compose

Viewed 3699

How to do my image to rotate infinitely?

This is my code but animation does not work

 val angle: Float by animateFloatAsState(
            targetValue = 360F,
            animationSpec = infiniteRepeatable(
                tween(2000))
        )
        Image(
            painter = painterResource(R.drawable.sonar_scanner),
            "image",
            Modifier
                .fillMaxSize()
                .rotate(angle),
            contentScale = ContentScale.Fit
        )
2 Answers

You can use the InfiniteTransition using rememberInfiniteTransition.
Something like

val infiniteTransition = rememberInfiniteTransition()
val angle by infiniteTransition.animateFloat(
    initialValue = 0F,
    targetValue = 360F,
    animationSpec = infiniteRepeatable(
        animation = tween(2000, easing = LinearEasing)
    )
)

Just a note.
Instead of using

Modifier.rotate(angle)

You can use

     Modifier
        .graphicsLayer {
            rotationZ = angle
        }

As you can check in the doc:

Prefer this version when you have layer properties backed by a androidx.compose.runtime.State or an animated value as reading a state inside block will only cause the layer properties update without triggering recomposition and relayout.

You should use the pre-defined API for infinite animations for such use cases in my opinion.

val infiniteTransition = rememberInfiniteTransition()
val angle by infiniteTransition.animateFloat(
    initialValue = 0f,
    targetValue = 360f,
    animationSpec = infiniteRepeatable(
        animation = keyframes {
            durationMillis = 1000
        }
    )
)
Related