Skip to content

Instantly share code, notes, and snippets.

@aabadaa
Forked from stevdza-san/AnimatedBorderCard.kt
Last active April 6, 2024 10:22
Show Gist options
  • Save aabadaa/aee63b5348778be58c9c595469ff1957 to your computer and use it in GitHub Desktop.
Save aabadaa/aee63b5348778be58c9c595469ff1957 to your computer and use it in GitHub Desktop.
Card with Animated Border built with Jetpack Compose.
// replace outer surface with clipToBounds modifier
@Composable
fun AnimatedBorderCard(
modifier: Modifier = Modifier,
shape: Shape = RoundedCornerShape(size = 0.dp),
borderWidth: Dp = 2.dp,
gradient: Brush = Brush.sweepGradient(listOf(Color.Gray, Color.White)),
animationDuration: Int = 10000,
onCardClick: () -> Unit = {},
content: @Composable () -> Unit
) {
val infiniteTransition = rememberInfiniteTransition(label = "Infinite Color Animation")
val degrees by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = animationDuration, easing = LinearEasing),
repeatMode = RepeatMode.Restart
),
label = "Infinite Colors"
)
Surface(
modifier = modifier
.clipToBounds()
.clickable { onCardClick() }
.padding(borderWidth)
.drawBehind {
rotate(degrees = degrees) {
drawCircle(
brush = gradient,
radius = size.width,
blendMode = BlendMode.SrcIn,
)
}
},
color = MaterialTheme.colorScheme.surface,
shape = shape
) {
content()
}
}
// create a modifier for animated border instead of a composable
@Composable
fun Modifier.animatedBorder(
backgroundColor: Color = MaterialTheme.colorScheme.surface,
borderWidth: Dp = 2.dp,
gradient: Brush = Brush.sweepGradient(listOf(Color.Gray, Color.White)),
animationDuration: Int = 10000,
) = composed {
val infiniteTransition = rememberInfiniteTransition(label = "Infinite Color Animation")
val degrees by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = animationDuration, easing = LinearEasing),
repeatMode = RepeatMode.Restart
),
label = "Infinite Colors"
)
clipToBounds()
.padding(borderWidth)
.drawBehind {
rotate(degrees = degrees) {
drawCircle(
brush = gradient,
radius = size.width,
blendMode = BlendMode.SrcIn,
)
}
}
.background(backgroundColor)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment