我需要实现可以离线呈现 HTML 的 WebView。 HTML 中可能会使用多种字体,我将它们全部下载到通过 context.getFilesDir()
获取的应用程序文件目录中。
我的目标:将这些字体文件“输入”到 WebView 中,以便呈现的 HTML 看起来正确。
到目前为止我尝试了什么。
通过以下方式将 HTML 绑定(bind)到 WebView:
baseUrl = "file:///data/user/0/com.myapp/files/fonts"; // this is for convenience, I don't hardcode like this in code
webView.loadDataWithBaseURL(baseUrl, html, "text/html; charset=utf-8", "UTF-8", null);
指定的文件夹包含所有下载的字体。
而且我还在 HTML 的 header 中添加了 @font-face
配置,如下所示:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style id="fonts">@font-face { font-family: Guttman Stam; src: url(/Guttman Stam.ttf); }</style>
</head>
<body>
<p><span style="background-color:#FFFFFF;font-family:Guttman Stam;font-size:26pt;">text</span></p>
</body>
</html>
我确定文件 /data/user/0/com.myapp/files/fonts/Guttman Stam.ttf
存在。
不幸的是,它不起作用。我还尝试在 @font-face
配置中提供完整路径,同时使用 null
和 ""
作为 WebView 的 baseUrl
,但运气不好。
所以,我有点迷路了。将不胜感激。
最佳答案
我用了很长时间,不确定是否适合你的情况,仅供引用
String finalDataToLoad = "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/font_helvetica.css\" />" + YOUR_HTML;
webView.loadDataWithBaseURL("file://" + outPutFolder, finalDataToLoad, "text/html", "utf-8", null);
outPutFolder 是我存放图像的地方
我在 Assets 文件夹中有字体
关于android - 在 Android WebView 中使用应用程序文件目录中的 TTF 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261438/