Skip to content

Instantly share code, notes, and snippets.

@theimpulson
Created August 30, 2023 05:52
Show Gist options
  • Save theimpulson/13f935a449f842aeb94095328f6091f0 to your computer and use it in GitHub Desktop.
Save theimpulson/13f935a449f842aeb94095328f6091f0 to your computer and use it in GitHub Desktop.
Modifier extension for shimmer animation in compose
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntSize
fun Modifier.shimmer(toShow: Boolean): Modifier = composed {
if (toShow) {
val shimmerColors = listOf(
Color.LightGray.copy(alpha = 0.6f),
Color.LightGray.copy(alpha = 0.2f),
Color.LightGray.copy(alpha = 0.6f),
)
var size by remember { mutableStateOf(IntSize.Zero) }
val transition = rememberInfiniteTransition(label = "")
val transitionAnimation = transition.animateFloat(
initialValue = 0f,
targetValue = 1000f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 1000,
easing = FastOutSlowInEasing
),
repeatMode = RepeatMode.Reverse
), label = ""
)
background(
brush = Brush.linearGradient(
colors = shimmerColors,
start = Offset.Zero,
end = Offset(x = transitionAnimation.value, y = transitionAnimation.value)
)
).onGloballyPositioned { size = it.size }
} else {
Modifier
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment