Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite rotation of an Image in Jetpack Compose

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
        )
like image 421
Solvek Avatar asked Mar 01 '23 12:03

Solvek


1 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.

like image 152
Gabriele Mariotti Avatar answered Mar 07 '23 23:03

Gabriele Mariotti