当某个布尔变量为 true 时,我的一个可组合项中的文本会被删除。如何在重组时为
TextStyle
中的这种变化设置动画,以便线条 淡入,而不是突然出现和消失?
@Composable
fun MyComposable(
completed: Boolean
) {
val textStyle = TextStyle(textDecoration = if (completed) TextDecoration.LineThrough else null)
Text(
text = title,
color = textColor,
style = textStyle,
modifier = Modifier.align(Alignment.CenterVertically)
)
不确定是否存在一种为
TextStyle
制作动画的方法。Box() {
AnimatedVisibility(
visible = !completed,
enter = fadeIn(
animationSpec = tween(durationMillis = duration)
),
exit = fadeOut(
animationSpec = tween(durationMillis = duration)
)) {
Text(
text = title,
style = TextStyle(textDecoration=null)
)
}
AnimatedVisibility(
visible = completed,
enter = fadeIn(
animationSpec = tween(durationMillis = duration)
),
exit = fadeOut(
animationSpec = tween(durationMillis = duration)
)) {
Text(
text = title,
style = TextStyle(textDecoration = TextDecoration.LineThrough),
)
}
}
Gabriele 的答案也是一个不错的解决方法,但也许更简单的方法是将
Text
和“Stroke
”放在一个盒子中,重叠。说,
@Composable
fun MyComposable(
completed: Boolean
) {
Box{
Text(
text = title,
color = textColor,
style = textStyle,
modifier = Modifier.align(Alignment.CenterVertically)
)
AnimatedVisibility (completed) {
Box(Modifier.width(1.dp)){
//Empty Box of unit width to serve as the stroke
// Add background modifiers to match the font color
}
}
}
您可以使用
lerp
函数的 TextStyle 重载。
fun lerp(start: TextStyle, stop: TextStyle, fraction: Float): TextStyle
此函数采用开始和结束文本样式,并根据提供的分数在它们之间进行动画处理。
用途:
val animatable = remember { Animatable(0f) }
Text(
text = title,
modifier = Modifier.weight(1f),
color = color.value,
style = lerp(
start = MaterialTheme.typography.bodyMedium,
stop = MaterialTheme.typography.headlineMedium,
fraction = animatable.value
)
)