如何在 Jetpack Compose 中为 TextStyle 制作动画?

问题描述 投票:0回答:3

当某个布尔变量为 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)
    )
android android-jetpack-compose android-jetpack-compose-text
3个回答
5
投票

不确定是否存在一种为

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),
        )
    }
}

enter image description here


1
投票

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
   }
  }
}


0
投票

您可以使用

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
           )
)

© www.soinside.com 2019 - 2024. All rights reserved.