如何在xamarin Android的Webview中设置自定义字体?

时间:2018-05-16 09:42:30

标签: xamarin.android

 webViewOfferes = FindViewById<WebView>(Resource.Id.webViewOffers);string start = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /><style  type='text/css'> li {line-height: 2;} @font-face {font-family: 'PlayfairDisplay-Regular';src: url('file:///Assets/fonts/PlayfairDisplay-Regular.ttf');} body{font-family:PlayfairDisplay-Regular;}</style></head><body>";
string end = "</body></html>";
webViewOfferes.LoadData(start + "<h3>My Custome Font:</h3>"+ end, "text/html", UTF32Encoding.ASCII.ToString());
                WebSettings Offersetting = webViewOfferes.Settings;
                Offersetting.DefaultFontSize = 13;

使用此代码无法获得所需的输出,请帮助

2 个答案:

答案 0 :(得分:0)

更改

file:///Assets/fonts/PlayfairDisplay-Regular.ttf

file:///android_asset/fonts/PlayfairDisplay-Regular.ttf

答案 1 :(得分:0)

这对于 Android和iOS均适用。

搜索了一段时间后,我找到了解决方案。基本上,它与您用HTML编写的代码直接相同。因此,我在HTML文件中创建了此HTML代码,将字体myfont.otf放在了同一文件夹中,并完成了这项工作:

<html>
    <head>
        <style type=text/css>
            @font-face {
                font-family: 'CustomFont';
                src: url('myfont.otf')
            }
            body {
                font-family: 'CustomFont';
            }
        </style>
    </head>
    <body>
        <p>This is some sentence with a custom font.</p>
    </body>
</html>

现在您要做的就是:

Android:

  • 将字体放入Android Assets文件夹中
  • 确保其构建操作为AndroidAsset
  • 将HTML字符串和字体名称(如果在子文件夹中,则带有路径,例如Fonts/myfont.otf)传递到WebView

iOS:

  • 将字体放入iOS Resources文件夹中
  • 确保其构建操作为BundleResource
  • 将HTML字符串和字体名称(如果在子文件夹中,则带有路径,例如Fonts/myfont.otf)传递到WebView

我为此做了一个辅助类:

public static class HtmlHelper
{
    public static string SurroundWithCustomFont(string htmlString, string fontPath)
    {
        return $@"
        <html>
            <head>
                <style type=text/css>
                    @font-face {{
                        font-family: 'CustomFont';
                        src: url('{fontPath}')
                    }}
                    body {{
                        font-family: 'CustomFont';
                    }}
                </style>
            </head>
            <body>
                {htmlString}
            </body>
        </html>";
    }
}