You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为TextDecoration.Underline设置自定义样式?

自定义下划线样式:TextDecoration.underline的局限性与替代方案

直接用TextDecoration.underline没法实现自定义下划线样式——它只能添加系统默认的下划线,无法调整颜色、粗细、偏移量、线条样式(实线/虚线/波浪线)这些自定义属性。

如果要实现自定义下划线,有几种实用方案:

1. 用AnnotatedString搭配SpanStyle

通过给文本片段添加带自定义样式的下划线Span,能精准控制下划线的各项属性:

val annotatedText = buildAnnotatedString {
    append("需要自定义下划线的文本")
    addStyle(
        style = SpanStyle(
            textDecoration = TextDecoration.Underline,
            textDecorationColor = Color.Red,
            textDecorationThickness = 2.dp.toSp(),
            textDecorationStyle = TextDecorationStyle.Dashed // 可选:Solid/Dashed/Wavy
        ),
        start = 0,
        end = length
    )
}

Text(text = annotatedText)

2. 借助Modifier.drawWithContent手动绘制

这种方式自由度最高,能完全自定义下划线的位置、形状甚至动画:

Text(
    text = "自定义下划线文本",
    style = MaterialTheme.typography.titleMedium.copy(
        fontWeight = FontWeight.W600,
        color = color
    ),
    modifier = Modifier.drawWithContent {
        drawContent()
        val textLayout = layoutResult
        textLayout.multiParagraph.forEachLine { lineIndex ->
            val lineBottom = textLayout.getLineBottom(lineIndex)
            drawLine(
                color = Color.Blue,
                start = Offset(textLayout.getLineLeft(lineIndex), lineBottom + 4.dp.toPx()),
                end = Offset(textLayout.getLineRight(lineIndex), lineBottom + 4.dp.toPx()),
                strokeWidth = 3.dp.toPx()
            )
        }
    }
)

3. 利用新版本Compose的underline参数

在较新的Jetpack Compose版本中,TextStyle新增了underline参数,可以直接配置自定义下划线:

textStyle = MaterialTheme.typography.titleMedium.copy(
    textAlign = TextAlign.Start,
    fontWeight = FontWeight.W600,
    color = color,
    underline = TextStyle.Underline(
        color = Color.Green,
        thickness = 1.5.dp,
        offset = 2.dp,
        style = TextDecorationStyle.Wavy
    )
)

内容的提问来源于stack exchange,提问作者Jeevan Rupacha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:57:08