【问题标题】:Access specific Android system fonts via CSS通过 CSS 访问特定的 Android 系统字体
【发布时间】:2013-11-07 01:24:04
【问题描述】:

我正在构建一个基于 Android 的 WebView 类的 webapp。目前,当我将它指向我的页面时,任何日文字符都会使用我想要的 DroidSansFallback 字体呈现。但是,当设备的语言更改为日语时,它会开始以 MTLmr3m.ttf 字体呈现日语字符,这有时会影响正在加载的网页的布局。经过一番研究,我发现这是由于fallback_fonts.xml系统文件中的这段代码的sn-p

<family>
    <fileset>
        <file lang="ja">MTLmr3m.ttf</file>
    </fileset>
</family>

大概我无法更改此系统文件,但有没有办法可以直接引用 DroidSansFallback.ttf 文件并将字体设置为字符串包含日文字符时的字体,以便无论语言如何都可以使用此字体设备设置为?

我尝试使用 WebViewClient 类中的 shouldInterceptRequest() 来捕获 css @font-face 声明中的虚拟协议,如下所示:src: url("font:Droid") format("truetype"); 并通过此代码以这种方式发送字体:

...
if (url.equals("font:Droid")){  
    File font = new File(Environment.getRootDirectory(),"/fonts/DroidSansFallback.ttf");
    InputStream is = new FileInputStream(font);
    String encoding="UTF-8";
    WebResourceResponse font = new WebResourceResponse("font/ttf",encoding,is);
    return font;
}
...

该方法捕获请求,但未按预期返回 WebResourceResponse。

我希望也许有一个解决方案,我可以以某种方式在 CSS 中引用我想要的字体。有什么建议吗?

【问题讨论】:

    标签: android css web-applications fonts webview


    【解决方案1】:

    我知道这肯定是迟到了,但它可能对某人有用。

    1)除非你有Root权限,否则你不能访问android根目录“/”。
    2)我相信你为字体使用了错误的 mimetype,使用这个“application/x-font-ttf

    所以您有 2 个选项,将您想要的字体放入资产中,或将您的字体复制到外部存储。
    我会展示第一种方式,其他方式留给你。

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url)
    {
        if(url.contains("font/droid.ttf"))
        {
             return getFontFromAsset();
        }
    }
    
    private WebResourceResponse getFontFromAsset()
    {       
        InputStream fontIn = null;
        try 
        {
            fontIn = yourContext.getAssets().open("DroidSansFallback.ttf");         
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        if(fontIn == null)
            return null;
        else
        {           
            WebResourceResponse response = new WebResourceResponse("application/x-font-ttf", "UTF-8", fontIn);
            return response;
        }       
    }
    

    你也可以为你的 css 使用类似的东西:

    @font-face { font-family: 'droid'; src: url('font/droid.ttf');} body { font-family: 'droid';}
    

    这是我的工作方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2011-04-18
      • 2019-07-15
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 2012-05-06
      相关资源
      最近更新 更多