- Step 1 :-
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.draw.shadow
import kotlinx.coroutines.delay
@Composable
fun LoadingAnimation(
modifier: Modifier = Modifier,
isLoading: Boolean = false, // Key to control the loading animation visibility
circleSize: Dp = 15.dp,
circleColor: Color = MaterialTheme.colors.primary,
spaceBetween: Dp = 10.dp,
travelDistance: Dp = 20.dp,
shadowSize: Dp = 8.dp, // Adding shadow size parameter
shadowColor: Color = Color.Gray // Adding shadow color parameter
) {
// Only show the animation if isLoading is true
if (isLoading) {
val circles = listOf(
remember { Animatable(initialValue = 0f) },
remember { Animatable(initialValue = 0f) },
remember { Animatable(initialValue = 0f) }
)
circles.forEachIndexed { index, animatable ->
LaunchedEffect(key1 = animatable) {
delay(index * 100L)
animatable.animateTo(
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = keyframes {
durationMillis = 1200
0.0f at 0 using LinearOutSlowInEasing
1.0f at 300 using LinearOutSlowInEasing
0.0f at 600 using LinearOutSlowInEasing
0.0f at 1200 using LinearOutSlowInEasing
},
repeatMode = RepeatMode.Restart
)
)
}
}
val circleValues = circles.map { it.value }
val distance = with(LocalDensity.current) { travelDistance.toPx() }
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center // Center content in the Box
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(spaceBetween)
) {
circleValues.forEach { value ->
Box(
modifier = Modifier
.size(circleSize)
.graphicsLayer {
translationY = -value * distance
}
.shadow(shadowSize, CircleShape, ambientColor = shadowColor) // Adding shadow to the circle
.background(
color = circleColor,
shape = CircleShape
)
)
}
}
}
}
}
- Step 2:-
Screenshot below :-
0 Comments