Embedding fonts in Xamarin Forms is the best way to use fonts, there is no need to add platform specific fonts and code. Its just adding one file and adding one attribute in shared code; that's it; we are ready to use fonts in our code.
How to add fonts in Xamarin Forms
In just three steps we shall add custom fonts in Xamarin forms and use it across all the platforms i.e. Android, iOS and UWP.
Before we get into Embedding fonts in Xamarin Forms, lets create a Xamarin Form project using following steps.
After creating project make sure it builds and we are able to see it on Emulator or on Mobile Device
After building the Xamarin Form and running it on simulator, we see simple (default) UI as follows
For Demo purpose we shall use a custom fonts named - Game Of Squids, you can download it using the link - https://www.dafont.com/game-of-squids.font
Add the font file (ttf or otf) to our project and mark it as embedded resource
Now to Embed or Add above custom font in Xamarin Forms, use following steps
Create folder structure - Resources > Fonts > GameOfSquids.ttf
Copy font and then click on properties as shown in following image
We have to make sure we select Build Action as Embedded Resource as per following image
If we don't set Build Action as Embedded resource then font added in Xamarin forms will not get applied. We have to make sure Font added in Xamarin forms had build Action set as Embedded Resource.
Add ExportFont attribute in our shared code
[assembly: ExportFont("GameOfSquids.ttf", Alias = "GameOfSquids")]
AssemblyInfo.cs code changes to following
using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] [assembly: ExportFont("GameOfSquids.ttf", Alias = "GameOfSquids")]
Now simply Consume the font in our controls
This is how we add custom fonts in Xamarin form