Created
October 18, 2024 11:00
-
-
Save MadFlasheroo7/152d2681ebe0db7329a7eaee5018f983 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@OptIn(ExperimentalLayoutApi::class) | |
@Composable | |
fun AnimateCharTextField( | |
value: String, | |
onValueChange: (String) -> Unit, | |
modifier: Modifier = Modifier, | |
textStyle: TextStyle = TextStyle(fontSize = 50.sp) | |
) { | |
val scope = rememberCoroutineScope() | |
val animatables = remember { mutableStateMapOf<Int, Animatable<Float, AnimationVector1D>>() } | |
BasicTextField( | |
value = value, | |
onValueChange = { newValue -> | |
val oldLength = value.length | |
val newLength = newValue.length | |
if (newLength > oldLength) { | |
// Character added | |
for (i in oldLength until newLength) { | |
animatables[i] = Animatable(0f) | |
scope.launch { | |
animatables[i]?.animateTo(1f, animationSpec = tween(300)) | |
} | |
} | |
} else if (newLength < oldLength) { | |
// Character(s) removed | |
for (i in newLength until oldLength) { | |
scope.launch { | |
animatables[i]?.animateTo(0f, animationSpec = tween(300)) | |
animatables.remove(i) | |
} | |
} | |
} | |
onValueChange(newValue) | |
}, | |
modifier = modifier, | |
textStyle = textStyle.copy(color = Color.Transparent), | |
decorationBox = { _ -> | |
FlowRow { | |
value.forEachIndexed { index, char -> | |
val scale = animatables[index]?.value ?: 1f | |
val alpha = animatables[index]?.value ?: 1f | |
Text( | |
text = "$char", | |
style = textStyle, | |
modifier = Modifier | |
.alpha(alpha) | |
.graphicsLayer { | |
scaleX = scale | |
scaleY = scale | |
transformOrigin = TransformOrigin.Center | |
} | |
) | |
} | |
} | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment