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

如何在Jetpack Compose应用中渲染文本样式与数学公式?

解决Jetpack Compose测验应用中的文本样式与LaTeX渲染问题

一、HTML文本样式渲染(斜体/加粗/下划线)

你已经通过HTML标签实现了基础样式,这里可以用Compose的AnnotatedString配合HTML解析来更灵活控制样式效果:

  • 先实现HTML转AnnotatedString的工具函数:
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import org.jsoup.Jsoup
import org.jsoup.nodes.Element

fun htmlToAnnotatedString(html: String): AnnotatedString {
    val doc = Jsoup.parse(html)
    return buildAnnotatedString {
        fun traverse(element: Element) {
            for (child in element.childNodes()) {
                if (child is Element) {
                    val start = length
                    traverse(child)
                    val end = length
                    when (child.tagName()) {
                        "b", "strong" -> addStyle(SpanStyle(fontWeight = FontWeight.Bold), start, end)
                        "i", "em" -> addStyle(SpanStyle(fontStyle = androidx.compose.ui.text.font.FontStyle.Italic), start, end)
                        "u" -> addStyle(SpanStyle(textDecoration = TextDecoration.Underline), start, end)
                    }
                } else {
                    append(child.toString())
                }
            }
        }
        traverse(doc.body())
    }
}
  • 在Compose中调用使用:
Text(text = htmlToAnnotatedString("What is <i>Mitochondria</i>?"))

二、LaTeX公式渲染

Compose原生不支持LaTeX,推荐两种可行方案:

方案1:基于本地WebView的Compose组件

将MathJax库文件放入项目src/main/assets目录,通过封装WebView渲染LaTeX,无需依赖外部链接:

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import android.webkit.WebView
import android.webkit.WebViewClient

@Composable
fun LatexView(latexCode: String) {
    AndroidView(
        modifier = Modifier.fillMaxWidth(),
        factory = { context ->
            WebView(context).apply {
                settings.javaScriptEnabled = true
                webViewClient = WebViewClient()
                loadDataWithBaseURL(
                    "file:///android_asset/",
                    """
                    <html>
                        <head>
                            <script src="mathjax.js"></script>
                        </head>
                        <body style="background-color: transparent; text-align: center;">
                            <p>\[
                            \begin{align}
                            $latexCode
                            \end{align}
                            \]</p>
                        </body>
                    </html>
                    """.trimIndent(),
                    "text/html",
                    "UTF-8",
                    null
                )
            }
        },
        update = { webView ->
            webView.loadDataWithBaseURL(
                "file:///android_asset/",
                """
                <html>
                    <head>
                        <script src="mathjax.js"></script>
                    </head>
                    <body style="background-color: transparent; text-align: center;">
                        <p>\[
                        \begin{align}
                        $latexCode
                        \end{align}
                        \]</p>
                    </body>
                </html>
                """.trimIndent(),
                "text/html",
                "UTF-8",
                null
            )
        }
    )
}

使用时传入你的LaTeX代码:

LatexView(latexCode = """
    A & = \frac{\pi r^2}{2} \\
    & = \frac{1}{2} \pi r^2
""".trimIndent())

方案2:Compose专用LaTeX库

使用为Compose开发的轻量LaTeX渲染库,无需WebView,性能更优:

  1. 在项目build.gradle中添加对应库的依赖
  2. 直接在Compose中调用组件:
@Composable
fun LatexFormula(formula: String) {
    LatexText(
        text = formula,
        textStyle = MaterialTheme.typography.bodyLarge
    )
}

三、混合场景处理

如果试题同时包含HTML样式和LaTeX公式,可以先解析HTML,用特定标记(如$$...$$)识别LaTeX块,将LaTeX部分替换为LatexView组件,HTML文本部分用htmlToAnnotatedString渲染,最后通过Column或FlowRow组合展示。

内容的提问来源于stack exchange,提问作者Roshan Mahato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:17:24