androidandroid-jetpack-composeandroid-animation

Convert float to dp in card's elevation in infiniteAnimation


Actually i am reading this article here my animation work fine but when i just used that value of animation in elevation then animation not even start . i have used that value of animation in shadow it work but in elevation do not work .

i think there is some issue in conversion of float in dp , i see many answer but they are in java .

now code is here

@Composable
fun Greeting(modifier: Modifier = Modifier) {
    Column(
        modifier =  Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally ,
        verticalArrangement = Arrangement.Center
    ){

        val infiniteTransition = rememberInfiniteTransition(label = "")
        val value by infiniteTransition.animateFloat(
            initialValue = 20f,
            targetValue = 200f,
            animationSpec = infiniteRepeatable(
                animation = tween(
                    durationMillis = 400,
                ),
                repeatMode = RepeatMode.Reverse
            ), label = ""
        )
        // Convert the floating-point value to a dimension value
        val elevationValue = with(LocalDensity.current) { value.dp }
        Card(
            modifier = Modifier.padding(30.dp)
                //.shadow(elevationValue)
                    ,
            elevation = CardDefaults.cardElevation(elevationValue) ,
            shape = RectangleShape,
        ){
            Text(
                text =
                "Infinite Animation ",
                fontSize = 30.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(10.dp)
            )
        }
    }
}

Solution

  • To convert from pixel to dp you can use value.toDp() function Density.

    /**
     * Convert an [Int] pixel value to [Dp].
     */
    @Stable
    fun Int.toDp(): Dp = (this / density).dp
    

    Dp is calculated with pixel value / density of device. Also there is animateDpAsState function that can animate between dp values.