Use custom font from res/font with WebView in Android

前端 未结 3 949
-上瘾入骨i
-上瘾入骨i 2020-12-31 09:13

I want to change font face of html string loaded into WebView similarly as mentioned in this question:

How to change font face of Webview in Android?

The dif

相关标签:
3条回答
  • 2020-12-31 09:37

    You can use the custom res font like this -

    <head>
    <style type="text/css">
        @font-face {
            font-family: MyFont;
            src: url("file:///res/font/myfont.ttf")
        }
        body {
            font-family: MyFont;
        }
    </style>
    

    0 讨论(0)
  • 2020-12-31 09:42

    I managed to load my local font from res/font directory. In my example i want to load italic opensans.

    My setup are as follow:

    1. css file inside assets directory
    2. use this for setting the font-face
        @font-face {
          font-family: 'opensans';
          src: url("file:///android_res/font/opensans_italic.ttf")
        }
    
        body {
          font-family: 'opensans';
          font-weight: 400;
        }
    
    1. Load the WebView using loadDataWithBaseUrl, for example:

      webView.loadDataWithBaseURL(null, yourHtmlContent, "text/html", "utf-8", null)

      But i have this at the the top of my html content: "<link rel='stylesheet' type='text/css' href='file:///android_asset/mycss.css' />”

      I hope it works too for your case.

    Edit:

    Add this in your proguard config to make it work in release mode.

    -keep class com.your.package.name.R$font { *; }

    0 讨论(0)
  • 2020-12-31 09:44

    Just tried and this works similarly to loading fonts from assets, you just need to change the base url to point to resources instead.

    Example HTML

    <html>
    <head>
        <style>
            @font-face {
                font-family: 'CustomFont';
                src: url('font/CustomFont.ttf');
            }
            #font {
                font-family: 'CustomFont';
            }
        </style>
    </head>
    <body>
        <p>No Font</p>
        <br />
        <p id="font">Font</p>
    </body>
    

    load this HTML into the webview using Webview#loadDataWithBaseURL(String, String, String, String, String), using file://android_res/ as the base url (first param)

    Example:

    webview.loadDataWithBaseURL("file:///android_res/", html, "text/html", "utf-8", null)
    

    Edit:

    If you're using proguard on your release builds you'll need to add extra rules to prevent the R class being renamed during the ProGuard process otherwise the WebView won't be able to find the font resource. Details can be found at this post

    0 讨论(0)
提交回复
热议问题