5

我目前重构了我的应用程序以使用可下载字体,因此我没有任何字体资产文件。我搜索了很多,我看到的唯一解决方案是将 FontFamily 设置在 CSS 文件中并将 src 指向 assets 文件夹。这对于可下载的字体是不可能的。

4

1 回答 1

0

使用 Android Downloadable Font 时,可以通过FontInfo.getUri()方法获取 ttf 字体文件的 URI。

FontsContractCompat.FontFamilyResult fontFamilyResult = FontsContractCompat.fetchFonts(view.getContext(), null, fontRequest);
Uri fontUri = fontFamilyResult.getFonts()[0].getUri();

您可以使用此 URI 将 ttf 文件缓存在您的应用程序空间中,您可以在 WebView HTML 和其他地方直接引用该文件。

如果要改用 URI 模型,请注意不能直接使用 FontsContractCompat 返回的 URI,因为加载的内容和此 URI 的基域不同,这可能违反 CORS 策略。您可以在 WebView HTML 中使用自定义 URI 模式并在 WebViewClient 的shouldInterceptRequest方法中拦截该请求,您可以从 FontsContractCompat 查询或本地缓存的字体文件返回的 URI 返回 InputStream(包装为 WebResourceResponse )。

像这样在 css 中形成 URI(需要将 myappscheme://com.myapp.demo 设置为内容的基本 url)

@font-face {
  font-family: Roboto;
  src: url('myappscheme://com.myapp.demo/fonts/name=Roboto');
}

在 WebViewClient 中。这只是一个演示代码片段。所以在这里抛出一些错误处理

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
    {
        Uri requestUri = request.getUrl();
        if (requestUri.getScheme()
                      .equals("myappscheme") && requestUri.getPath()
                                                          .startsWith("fonts"))
        {
            Context context = view.getContext();
            File fontFile = new File(context.getExternalCacheDir(), requestUri.getQueryParameter("name") + ".ttf");
            if (!fontFile.exists())
            {
                FontRequest fontRequest = new FontRequest(
                    "com.google.android.gms.fonts",
                    "com.google.android.gms",
                    requestUri.getQuery(),
                    R.array.com_google_android_gms_fonts_certs);

                FontsContractCompat.FontFamilyResult fontFamilyResult = FontsContractCompat.fetchFonts(view.getContext(), null, fontRequest);
                if (fontFamilyResult.getStatusCode() == FontsContractCompat.FontFamilyResult.STATUS_OK)
                {
                    InputStream gFont = context.getContentResolver()
                                               .openInputStream(fontFamilyResult.getFonts()[0].getUri());
                    fontFile.createNewFile();
                    ByteStreamsKt.copyTo(gFont, new FileOutputStream(fontFile), 4096);
                }
            }
            return new WebResourceResponse("application/octet-stream", null, new FileInputStream(fontFile));
        }
    }
于 2019-12-17T07:47:05.917 回答