Last active
June 5, 2020 11:03
-
-
Save dgomolka/c8af2ea84d8ec95eda9aa861e38e955f to your computer and use it in GitHub Desktop.
Simple Modifier for creating skeleton view using Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.Composable | |
import androidx.compose.state | |
import androidx.ui.animation.animate | |
import androidx.ui.core.ContentDrawScope | |
import androidx.ui.core.DrawModifier | |
import androidx.ui.core.Modifier | |
import androidx.ui.core.composed | |
import androidx.ui.geometry.Size | |
import androidx.ui.graphics.Color | |
import androidx.ui.material.MaterialTheme | |
import androidx.ui.unit.Dp | |
import androidx.ui.unit.dp | |
private val SkeletonCornerRadius = 3.dp | |
private const val SkeletonInitialHeightMultiplier = 1f | |
@Composable | |
fun Modifier.skeleton( | |
shouldShowSkeleton: Boolean, | |
animateWidth: Boolean = false, | |
animateHeight: Boolean = true, | |
heightMultiplier: Float = SkeletonInitialHeightMultiplier, | |
color: Color = MaterialTheme.colors.primary, | |
cornerRadius: Dp = SkeletonCornerRadius | |
): Modifier = composed { | |
val isInitial = state { true } | |
val alpha = animate(if (shouldShowSkeleton) 1f else 0f) | |
val initialAlpha = animate(if (isInitial.value) 0f else 1f) | |
val width = state { 0f } | |
val height = state { 0f } | |
val widthChanged = state { 0f } | |
val heightChanged = state { 0f } | |
if (animateWidth) { | |
width.value = | |
animate(if (width.value != widthChanged.value) widthChanged.value else width.value) | |
} | |
if (animateHeight) { | |
height.value = | |
animate(if (height.value != heightChanged.value) heightChanged.value else height.value) | |
} | |
isInitial.value = false | |
this + object : DrawModifier { | |
override fun ContentDrawScope.draw() { | |
if (animateWidth) { | |
widthChanged.value = size.width | |
} | |
if (animateHeight) { | |
heightChanged.value = size.height | |
} | |
if ((initialAlpha <= 1f && !shouldShowSkeleton) || alpha < 1f) | |
drawContent() | |
when { | |
alpha != 0f -> { | |
val widthToUse = if (animateWidth) width.value else size.width | |
val heightToUse = if (animateHeight) height.value else size.height | |
drawRoundRect( | |
color, | |
radiusX = cornerRadius.toPx().value, | |
radiusY = cornerRadius.toPx().value, | |
alpha = if (initialAlpha != 1f) initialAlpha else alpha, | |
size = Size(widthToUse, heightToUse * heightMultiplier) | |
) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment