Custom font in Xamarin Forms WebView

shaun pryszlak 26 Reputation points
2021-04-13T11:38:20.387+00:00

I have a forms app (android and ios) and the UI is all html and now, I want to use a custom font in it. I have added it to the shared solution and marked it as an embedded resource.

I have exported it
[assembly: ExportFont("Cassiopeia.ttf", Alias = "Cassiopeia")]

Then in my UI css I have

body {
font-family: "Cassiopeia", Times, serif;
padding-left: 50px;
padding-right: 50px;
}

It is just coming out as times, which I assume means it isn't finding the new font.

Any ideas?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,273 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. shaun pryszlak 26 Reputation points
    2021-04-14T10:51:51.053+00:00

    I got it working. In the end I ...

    1. Copied it to the "Assets/Fonts" folder in the android project. That sets the Build Action to AndroidAsset. I don't think you need the "Always copy" as all my other Assets get copied over ok.
    2. I split my .css file into two. One has the platform specific bits in it. See below. The other has all the other css. Simply import both files into your html as normal. These live in the Assets folder as well.

    This tells the app where to find the font file. Its location is specific to android, so i put it in its own file. This was case sensitive when it came to the Font folder name.
    @font-face {
    font-family: Cassiopeia;
    src: url(file:///android_asset/Fonts/Cassiopeia.ttf);
    }

    Then in the other css file I put
    body {
    font-family: "Cassiopeia", Times, serif;
    padding-left: 50px;
    padding-right: 50px;
    }

    This causes the font to be the default font.

    1 person found this answer helpful.

  2. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 66,561 Reputation points Microsoft Vendor
    2021-04-13T12:50:34.02+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Where is your html page? In local storage or Assets folders?

    Here is the step to load custom font in webview.:

    1. create fonts folder in Assets folder and put your font(ttf,otf) file in Assets/fonts folder.
    2. Build action of font file : AndroidAsset , Copy to output directory: Always copy
    3. initialize html string for webview i.e You can refer to this thread: https://forums.xamarin.com/discussion/33404/set-custom-font-in-webview

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments