Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How to Achieve Translate Animation in Jetpack Compose?


I am trying to achieve translate animation in Jetpack compose but i am not able to find Suitable Source for this.Can any one Help me to achieve translate Animation in jetpack compose in which i can set start and edning positionl Manually..


Solution

  • The alternative of translate animation in jetpack compose is OFFSET ANIMATION yes, I was able to achieve this through offset animation.I am sharing the code below with comments in detail so it will be easier for the reader to understand it

    val coroutineScope = rememberCoroutineScope()
    val offsetX = remember { Animatable(0f) }
    val offsetY = remember { Animatable(0f) }
    
    Image(
        painter = rememberDrawablePainter(
            ContextCompat.getDrawable(
                context,
                R.drawable.image
            )
        ),
        contentDescription = "image", 
        contentScale = ContentScale.Crop,
        modifier = Modifier
            .offset {
                IntOffset(
                    offsetX.value.toInt(),
                    offsetY.value.toInt()
                )
            }
            .width(300.dp)
            .height(300.dp)
    )
    
    // Finally run the animation on clicking a button or whenever you want to start it.
    coroutineScope.launch {
        launch {
            offsetXFirst.animateTo(
                targetValue = targetValue,
                animationSpec = tween(
                    durationMillis = 2000,
                    delayMillis = 0
                )
            )
        }
    
        launch {
            offsetYFirst.animateTo(
                targetValue = size.height.toFloat(),
                animationSpec = tween(
                    durationMillis = 2000,
                    delayMillis = 0
                )
            )
        }
    }