Create Bounce Animation on Touch in Android Jetpack Compose

27 Jul, 2021
Prerequisites:
Basic knowledge of Kotlin
Basic Knowledge of Jetpack Compose
In this article, we will take a look at how to create a bounce animation when the user taps anything, further it can be extended as per the use of the App. Here’s a sample gif demonstrating the animation.
Step 1: Create a New Project (Or use it in the existing Compose project)
To create a new project in the Android Studio Canary version, refer to the article How to Create a new Project in the Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt
Create an enum class that stores the states (Released / Pressed).
Kotlin
enum class BounceState { Pressed, Released }
 Step 3: Adding Animation 
Create a composable function Bounce, add the following code 
Kotlin
var currentState: BounceState by remember { mutableStateOf(BounceState.Released) }val transition = updateTransition(targetState = currentState, label = "animation") val scale: Float by transition.animateFloat(        transitionSpec = { spring(stiffness = 900f) }, label = "") { state ->         // When the item is pressed , reduce          // its size by 5% or make its size 0.95          // of its original size        // Change this value to see effect        if (state == BounceState.Pressed) {            0.95f        } else {            // When the item is released ,              // make it of its original size            1f      }}
Then use the pointerInputScope modifier to detect gestures and apply the animation, add the following code to the Bounce composable as well. 
Kotlin
// Basic compose Box LayoutBox(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {Column(modifier = Modifier            .pointerInput(Unit) {                detectTapGestures(onPress = {                     // Set the currentState to Pressed                      // to trigger Pressed animation                    currentState = BounceState.Pressed                     // Waits for the tap to release                      // before returning the call                    tryAwaitRelease()                     // Set the currentState to Release                      // to trigger Release animation                    currentState = BounceState.Released                })            }) {            Image(                painter = painterResource(id = R.drawable.gfg),                contentDescription = "gfg",                modifier = Modifier.graphicsLayer {                    scaleX = scale                    scaleY = scale              })      }}
 And we are done. This is the final code for MainActivity.kt file. 
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.animation.core.Transitionimport androidx.compose.animation.core.animateFloatimport androidx.compose.animation.core.springimport androidx.compose.animation.core.updateTransitionimport androidx.compose.foundation.Imageimport androidx.compose.foundation.gestures.detectTapGesturesimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.material.MaterialThemeimport androidx.compose.material.Surfaceimport androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.tooling.preview.Previewimport com.shaun.bounceanimation.ui.theme.BounceAnimationTheme class MainActivity : ComponentActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContent {            BounceAnimationTheme {                Surface(color = MaterialTheme.colors.background) {                    Bounce()                }            }        }    }} enum class BounceState { Pressed, Released } @Preview(showBackground = true)@Composablefun Bounce() {    var currentState: BounceState by remember { mutableStateOf(BounceState.Released) }    val transition = updateTransition(targetState = currentState, label = "animation")    val scale: Float by transition.animateFloat(        transitionSpec = { spring(stiffness = 900f) }, label = ""    ) { state ->         // When the item is pressed ,reduce its size          // by 5% or make its size 0.95 of its original size        // Change this value to see effect        if (state == BounceState.Pressed) {            0.95f        } else {            // When the item is released ,             // make it of its original size            1f        }    } // Basic compose Box LayoutBox(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column(modifier = Modifier            .pointerInput(Unit) {                detectTapGestures(onPress = {                     // Set the currentState to Pressed                      // to trigger Pressed animation                    currentState = BounceState.Pressed                     // Waits for the tap to release                      // before returning the call                    tryAwaitRelease()                     // Set the currentState to Release                      // to trigger Release animation                    currentState = BounceState.Released                })            }) {            Image(                painter = painterResource(id = R.drawable.gfg),                contentDescription = "gfg",                modifier = Modifier.graphicsLayer {                    scaleX = scale                    scaleY = scale              })        }    }}
Output:
Get the complete project from here.
 
varshagumber28
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android