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

如何为Jetpack Compose的AnnotatedString添加虚线下划线?

如何为AnnotatedString设置虚线下划线样式?

默认的TextDecoration.Underline只能生成实线下划线,要实现虚线下划线,需要自定义TextDecoration来实现:

  1. 先创建自定义的虚线下划线装饰
val dottedUnderline = TextDecoration.Custom(
    object : TextDecoration.LinePainter {
        override fun Paint.drawLine(
            start: Offset,
            end: Offset,
            density: Density
        ) {
            // 配置虚线参数:数组内依次是线段长度、间隔长度,第二个参数是偏移量
            pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 5f), 0f)
            drawLine(start, end)
        }
    }
)
  1. 在buildAnnotatedString中使用这个自定义装饰
buildAnnotatedString {
    append(text1)
    append(text2)

    // 为text3添加虚线下划线
    withStyle(style = SpanStyle(textDecoration = dottedUnderline)) {
        append(text3)
    }
}

你可以通过修改dashPathEffect的参数来调整虚线的线段长度、间隔大小,适配不同的UI需求。

内容的提问来源于stack exchange,提问作者Vivek Mangal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:34:51