Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Animation effect with Jetpack Compose

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to achieve animation effects on Jetpack Compose. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Overview

Compose provides a large number of api to support animation, through which we can easily achieve animation effects.

Ps: the principle of these api is very similar to that of Flutter, but very different from the original api.

You can take a look at a zoom in and out animation implemented in compose in advance, which is still relatively smooth in general:

Low-level animation APIanimate*AsState

Types of attributes that can be handled: Float, Color, Dp, Size, Bounds, Offset, Rect, Int, IntOffset and IntSize

Through animate*AsState, we can achieve the animation effect of a single attribute. We only need to provide the target value to automatically transition from the current progress animation to the target value.

Achieve magnification of animation

1. Code

@ Composablefun animSize () {val enable = remember {mutableStateOf (true)} val size = animateSizeAsState (targetValue = if (enable.value) Size (50f, 50f) else Size (300f, 300f) Column (modifier = Modifier.fillMaxSize (1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {Image (modifier = Modifier .size (size.value.width.dp) Size.value.height.dp) .clickable {enable.value =! enable.value}, painter = painterResource (id = R.drawable.apple), contentDescription = "")}}

two。 Realize the effect

Realize color change animation

1. Code

@ Composablefun animColor () {val enable = remember {mutableStateOf (true)} val colors = animateColorAsState (targetValue = if (enable.value) Color.Green else Color.Red) val size = animateIntSizeAsState (targetValue = if (enable.value) IntSize (100,100) else IntSize (300,300) Column (modifier = Modifier.fillMaxWidth (1f), horizontalAlignment = Alignment.CenterHorizontally VerticalArrangement = Arrangement.Center) {Box (modifier = Modifier .size (size.value.width.dp, size.value.height.dp) .height (400.dp) .background (color = colors.value) Shape = if (enable.value) RectangleShape else CircleShape)) {}

two。 Effect.

Use Animatable to realize the effect of color change

Animatable is a value container, and we can animate it by calling animateTo. Opening the animation again during the execution of the animation will interrupt the current animation.

The value change during the execution of Animatable animation is performed in the collaborative process, so animateTo is a pending operation.

1. Code

@ Composablefun animChangeColor () {val color = remember {Animatable (Color.Red)} val state = remember {mutableStateOf (true)} LaunchedEffect (state.value) {color.animateTo (if (state.value) Color.Red else Color.Magenta)} Box (Modifier.fillMaxSize (1f), contentAlignment = Alignment.Center) {Box (modifier = Modifier. Background (color.value) Shape = RoundedCornerShape (30.dp) .size (200.dp) .clickable {state.value =! state.value}, contentAlignment = Alignment.Center) {Text (text = "color animation", style = TextStyle (color = Color.White) FontSize = 40.sp))}

two。 Effect.

Use updateTransition to realize color and fillet animation

Use updateTransition to achieve the effect of multiple animation combinations.

For example, we can perform both size and color changes during animation.

In this example, we define an enumeration to control the animation, and enumerations can define multiple states corresponding to the animation.

1. Code

@ Composablefun animupdateTransition () {var state by remember {mutableStateOf (BoxState.Collapsed)} val transition = updateTransition (targetState = state Label = "") val round = transition.animateDp (label = ") {when (it) {BoxState.Collapsed-> 40.dp BoxState.Expanded-> 100.dp}} val color = transition.animateColor (label =") {when (it) {BoxState.Collapsed-> Color.Red BoxState.Expanded-> Color.Green }} Box (Modifier.fillMaxSize (1f) ContentAlignment = Alignment.Center) {Box (modifier = Modifier .size (300.dp) .background (color.value Shape = RoundedCornerShape (corner = CornerSize (round.value)) .clickable {state = if (state = = BoxState.Collapsed) BoxState.Expanded else BoxState.Collapsed}, contentAlignment = Alignment.Center) {Text (text = "Click to start the animation", style = TextStyle (color = Color.White) FontSize = 20.sp)} private enum class BoxState {Collapsed, Expanded}

two。 Effect.

RememberInfiniteTransition

The use of rememberInfiniteTransition is basically the same as that of updateTransition, except that once the animation of rememberInfiniteTransition starts, it will run again and again, and only when the animation is removed can it end.

1. Code

@ Composablefun rememberInfiniteTransition1 () {val infiniteTransition = rememberInfiniteTransition () val color by infiniteTransition.animateColor (initialValue = Color.Red, targetValue = Color.Green, animationSpec = infiniteRepeatable (animation = tween (1000, easing = LinearEasing), repeatMode = RepeatMode.Reverse) Box (Modifier.fillMaxSize (1f) ContentAlignment = Alignment.Center) {Box (Modifier .fillMaxSize (0.8f) .background (color), contentAlignment = Alignment.Center) {Text (text = "official account: original Android No plagiarism ", style = TextStyle (color = Color.White, fontSize = 30.sp)}

two。 Effect.

TargetBasedAnimation

TargetBasedAnimation can control the execution time of the animation and delay the opening of the animation for a period of time.

1. Code

@ Composablefun animTargetBasedAnimation () {var state by remember {mutableStateOf (0)} val anim = remember {TargetBasedAnimation (animationSpec = tween (2000), typeConverter = Float.VectorConverter, initialValue = 100f TargetValue = 300f)} var playTime by remember {mutableStateOf (0L)} var animationValue by remember {mutableStateOf (0)} LaunchedEffect (state) {val startTime = withFrameNanos {it} println ("enter the protocol:") do {playTime = withFrameNanos {it}-startTime animationValue = anim.getValueFromNanos (playTime). ToInt () } while (! anim.isFinishedFromNanos (playTime))} Box (modifier = Modifier.fillMaxSize (1f)) ContentAlignment = Alignment.Center) {Box (modifier = Modifier .size (animationValue.dp) .background (Color.Red,shape = RoundedCornerShape (animationValue/5)) .clickable {state++}, contentAlignment = Alignment.Center) {Text (text = animationValue.toString (), style = TextStyle (color = Color.White,fontSize = (animationValue/5) .sp))}

two。 Effect.

Custom Animation AnimationSpec

AnimationSpec can customize the behavior of the animation, and the effect is similar to the estimator in the native animation.

SpringSpec spring effect

1. Code

@ Composablefun animSpring () {val state = remember {mutableStateOf (true)} var value = animateIntAsState (targetValue = if (state.value) 300 else 100, animationSpec = spring (dampingRatio = Spring.DampingRatioHighBouncy, stiffness = Spring.StiffnessVeryLow) Box (Modifier .fillMaxSize (1f) .padding (start = 30.dp) ContentAlignment = Alignment.CenterStart) {Box (Modifier .width (value.value.dp) .height (80.dp) .background (Color.Red, RoundedCornerShape (topEnd = 30.dp, bottomEnd = 30.dp)) .clickable {state.value =! state.value} ContentAlignment = Alignment.CenterStart) {Text (text = "ha ha", style = TextStyle (color = Color.White, fontSize = 20.sp))}

two。 Effect.

TweenSpec animation time can be controlled

1. Code

@ Composablefun animTweenSpec () {val state = remember {mutableStateOf (true)} val value = animateIntAsState (targetValue = if (state.value) 300 else 100, animationSpec = tween (durationMillis = 1500, delayMillis = 200, easing = LinearEasing) Box (Modifier .fillMaxSize (1f) .padding (start = 50.dp) ContentAlignment = Alignment.CenterStart) {Box (Modifier .width (value.value.dp) .height (100.dp) .background (Color.Red, RoundedCornerShape (topEnd = 30.dp) BottomEnd = 30.dp) .clickable {state.value =! state.value}) {}

two。 Effect.

FrameSpec

1. Code

@ Composablefun animkeyframesSpec () {var state by remember {mutableStateOf (true)} val value by animateIntAsState (targetValue = if (state) 300 else 100, animationSpec = keyframes {durationMillis = 2000 0 at 700 with LinearOutSlowInEasing 700 at 1400 with FastOutLinearInEasing 1400 at 2000}) Box (Modifier.fillMaxSize (1f) ContentAlignment = Alignment.CenterStart) {Box (Modifier .width (value.dp) .height (100.dp) .background (Color.Red, RoundedCornerShape (topEnd = 30.dp, bottomEnd = 30.dp)) .clickable {state =! state}) {}

two。 Effect.

RepeatableSpec realizes a limited number of repeated animations

Automatically stop after performing a limited number of animations

1. Code

@ Composablefun animrepeatableSpec () {var state by remember {mutableStateOf (true)} val value by animateIntAsState (targetValue = if (state) 300 else 100, animationSpec = repeatable (iterations = 5 iterations / number of times the animation is repeated Execute as many times as you set animation = tween (durationMillis = 1000), repeatMode = RepeatMode.Reverse) Box (Modifier .fillMaxSize (1f) .padding (start = 30.dp) ContentAlignment = Alignment.CenterStart) {Box (Modifier .width (value.dp) .height (100.dp) .background (Color.Red, RoundedCornerShape (topEnd = 30.dp, bottomEnd = 30.dp)) .clickable {state =! state}) {}

two。 Effect.

Five iterations are set in the code, so the animation ends after five iterations.

InfiniteRepeatableSpec executes an unlimited number of animations

The animation will be executed indefinitely until the view is removed

1. Code

@ Composablefun animinfiniteRepeatableSpec () {var state by remember {mutableStateOf (true)} val value by animateIntAsState (targetValue = if (state) 300 else 100, animationSpec = infiniteRepeatable (animation = tween (durationMillis = 1000), repeatMode = RepeatMode.Reverse)) Box (Modifier .fillMaxSize (1f) .padding (start = 30.dp) ContentAlignment = Alignment.CenterStart) {Box (Modifier .width (value.dp) .height (100.dp) .background (Color.Red, RoundedCornerShape (topEnd = 30.dp) BottomEnd = 30.dp) .clickable {state =! state}) {Text (text = "official account: Android original No reprinting ")}

two。 Effect.

Easing

Easing is similar to the differentiator in our native animation.

There are several options:

FastOutSlowInEasing

LinearOutSlowInEasing

FastOutLinearInEasing

LinearEasing

CubicBezierEasing

The effects of these implementations are very different from the animation differentiators native to android, and they don't even have any effect, so I won't put the code. Readers with clear reasons can contact me.

Achieve results:

AnimationVector

Most Compose animation API supports Float, Color, Dp, and other basic data types as animation values out of the box, but sometimes we need to add animation effects to other data types (including our custom types)

In this example, the color and size transformation animation is realized.

In the code, we define an AnimSize class. The first parameter in the class is color data, and the second parameter is size data. During the execution of the animation, colleagues will change the color and size effect of the control.

1. Code

@ Composablefun animAnimationVector () {var state by remember {mutableStateOf (true)} val value by animateValueAsState (targetValue = if (state) AnimSize (0xffff5500, 100f) else AnimSize (0xff00ff00, 300f), typeConverter = TwoWayConverter (convertToVector = {/ / AnimationVector2D (target.color.toFloat (), target.size) AnimationVector2D (it.color.toFloat (), it.size)} ConvertFromVector = {AnimSize (it.v1.toLong (), it.v2)}) println ("Color: ${value.color}") Box (modifier = Modifier.fillMaxSize (1f) .padding (30.dp) ContentAlignment = Alignment.Center) {Box (modifier = Modifier .size (value.size.dp) / / .size (300.dp) .background (Color (value.color)) RoundedCornerShape (30.dp)) .clickable {state =! state}) {}} data class AnimSize (val color: Long, val size: Float)

two。 Effect.

The disadvantage is that there is flickering during the implementation of color changes.

Advanced animation

Advanced animation generally refers to the animation with high encapsulation, which is relatively easy to use, and there are three main types:

Because the advanced animation effect is not obvious, it is very difficult for gif to show the effect, so I will not put the code and effect diagram here.

AnimatedVisibility

AnimateContentSize

Crossfade

This is the end of this article on "how to achieve animation in Jetpack Compose". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report