animate
public suspend fun animate(
initialValue: Float,
targetValue: Float,
initialVelocity: Float = 0f,
animationSpec: AnimationSpec<Float> = spring(),
block: (value: Float, velocity: Float) -> Unit,
)
Target based animation that animates from the given initialValue
towards the targetValue
,
with an optional initialVelocity
. By default, a spring
will be used for the animation. An
alternative animationSpec
can be provided to replace the default spring
.
This is a convenient method for Float animation. If there's a need to access more info related to
the animation such as start time, target, etc, consider using AnimationState.animateTo
. To
animate non-Float
data types, consider the animate
overload/variant for generic types.
Parameters
initialValue | The initial value to animate from. |
targetValue | The target value to animate to. |
initialVelocity | The velocity to use for the animation. 0f by default. |
animationSpec | The animation configuration that will be used. spring by default. |
block | Will be invoked on every frame with the current value and velocity of the animation for that frame. |
public suspend fun <T, V : AnimationVector> animate(
typeConverter: TwoWayConverter<T, V>,
initialValue: T,
targetValue: T,
initialVelocity: T? = null,
animationSpec: AnimationSpec<T> = spring(),
block: (value: T, velocity: T) -> Unit,
)
Target based animation for animating any data type T
, so long as T
can be converted to an
AnimationVector
using typeConverter
. The animation will start from the initialValue
and
animate to the targetValue
value. The initialVelocity
will be derived from an all-0
AnimationVector
unless specified. animationSpec
can be provided to create a specific look and
feel for the animation. By default, a spring
will be used.
This is a convenient method for target-based animation. If there's a need to access more info
related to the animation such as start time, target, etc, consider using
AnimationState.animateTo
.
Code Examples
suspendAnimateFloatVariant
fun suspendAnimateFloatVariant() {
@Composable
fun InfiniteAnimationDemo() {
// Create a mutable state for alpha, and update it in the animation.
val alpha = remember { mutableStateOf(1f) }
LaunchedEffect(Unit) {
// Animate from 1f to 0f using an infinitely repeating animation
animate(
initialValue = 1f,
targetValue = 0f,
animationSpec =
infiniteRepeatable(animation = tween(1000), repeatMode = RepeatMode.Reverse),
) { value, /* velocity */ _ ->
// Update alpha mutable state with the current animation value
alpha.value = value
}
}
Box(Modifier.fillMaxSize()) {
Icon(
Icons.Filled.Favorite,
contentDescription = null,
modifier =
Modifier.align(Alignment.Center)
.graphicsLayer(scaleX = 3.0f, scaleY = 3.0f, alpha = alpha.value),
tint = Color.Red,
)
}
}
}