Home > Net >  Rotate Animation Compose
Rotate Animation Compose

Time:08-09

How can I make the same animation be applied to the picture when the button is clicked? I don't use angle changes all the time. That is, the picture should have the same animation every time the button is clicked?

 var angle by remember { mutableStateOf(0f) }
val rotate by animateFloatAsState(
    targetValue = angle,
    animationSpec = spring(
        dampingRatio = Spring.DampingRatioHighBouncy,
    )
)
val imageId = state.diceImageId
Column(
    modifier = modifier,
    horizontalAlignment = Alignment.CenterHorizontally
) {

    Image(
        painter = painterResource(id = imageId),
        contentDescription = imageId.toString(),
        modifier = Modifier.rotate(rotate)
    )
    Spacer(modifier = Modifier.height(16.dp))
    Button(onClick = {
      //i think it's wrong
        angle  = 360f
    }) {
        Text(text = stringResource(id = R.string.roll_button_text))
    }
}

CodePudding user response:

You can use Animatable class for this

val animatableRotation = remember {Animatable(rotationInitial)}


val coroutineScope = rememberCoroutineScope()

coroutineScope.launch{
   // Animate from current value to target value(rotation param) of Animatable
   animatableRotation.animateTo(rotation)
}

To apply this rotation to Image

Image(
    painter = painterResource(id = imageId),
    contentDescription = imageId.toString(),
    modifier = Modifier.rotate(animatableRotation.value)
)
  • Related