Last active
September 8, 2023 02:28
-
-
Save giovanileitevitor/b8073eb79ee27fab8ae8855b952cd6e8 to your computer and use it in GitHub Desktop.
Animated Border extension for composable elements
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
//EXTENSION FOR COMPOSABLE ELEMENTS | |
fun Modifier.dashedBorder( | |
color: Color, | |
strokeWidth: Dp, | |
strokeLength: Dp, | |
animate: Boolean = true, | |
) = composed( | |
factory = { | |
val density = LocalDensity.current | |
val strokeWidthPx = density.run { strokeWidth.toPx() } | |
val strokeLengthPx = density.run { strokeLength.toPx() } | |
var lastAnimValue by remember { mutableFloatStateOf(0f) } | |
val anim = remember(animate) { Animatable(lastAnimValue) } | |
LaunchedEffect(animate) { | |
if (animate) { | |
anim.animateTo( | |
targetValue = (strokeLengthPx * 2 + lastAnimValue), | |
animationSpec = infiniteRepeatable( | |
animation = tween(1000, easing = LinearEasing), | |
repeatMode = RepeatMode.Restart, | |
) | |
) { | |
lastAnimValue = value // store the anim value | |
} | |
} | |
} | |
this.then( | |
Modifier.drawWithCache { | |
onDrawBehind { | |
val stroke = Stroke( | |
width = strokeWidthPx, | |
pathEffect = PathEffect.dashPathEffect( | |
intervals = floatArrayOf(strokeLengthPx, strokeLengthPx), | |
phase = anim.value | |
) | |
) | |
drawRect( | |
color = color, | |
style = stroke | |
) | |
} | |
} | |
) | |
} | |
) | |
//HOW TO USE THIS COMPOSABLE EXTENSION | |
//To use this extension with your Composable elements such as Image(), Text() or other elements, | |
//all you need to do is to override your Modifier propertie. | |
Text( | |
text = "B3", | |
modifier = Modifier | |
.dashedBorder( | |
color = Color.Blue, | |
strokeLength = 40.dp, | |
strokeWidth = 2.dp, | |
animate = true | |
) | |
) | |
Image( | |
imageVector = ImageVector.vectorResource(id = R.drawable.ic_salvar), | |
contentDescription = "icone", | |
modifier = Modifier.dashedBorder( | |
color = Color.Red, | |
strokeLength = 40.dp, | |
strokeWidth = 2.dp, | |
animate = true | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment