question

shaunpryszlak-2817 avatar image
0 Votes"
shaunpryszlak-2817 asked LeonLu-MSFT edited

Custom font in Xamarin Forms WebView

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?

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered

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.









5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

shaunpryszlak-2817 avatar image
0 Votes"
shaunpryszlak-2817 answered LeonLu-MSFT edited

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your sharing.

0 Votes 0 ·