Xamarin.Forms and the most easiest way to use custom fonts
With the new version of Xamarin.Forms, version 4.5.53o and up. Adding and using the custom font in your Xamarin.Forms project is easier than ever before! If you are interested in seeing a new way of doing that, this blog post will show you how to do it. This works with Android, iOS and UWP.
First of all, you need to use Xamarin.Forms package with version 4.5.53o and up. For this simple and quick blog post, I will use the basic blank Xamarin.Forms project with one page, MainPage.xaml.
Let's start with the tutorial, first thing...
Download and add font file in your project.
My project structure looks like this:
I have created the folder called "Resources" and inside of it I have another folder which will hold my fonts. You don't need to structure it in this way, but I like this clean separation of files. As I already wrote, you can put the font file anywhere in your main/core project and you will be perfectly fine.
I found this Libre Baskerville font on Google Fonts and decided to use it, in this blog post, you can download it here if you want. 😁
The important step is to set Build Action to EmbeddedResource. So right-click on it and under Advanced category set build action like this.
Don't forget about ExportFont("...") attribute.
For me the best place to add this attribute is inside of AssemblyInfo.cs file, this is a very important step so don't forget about it. 😊
My AssemblyInfo.cs looks like this:
... also you can use Alias property to define some more friendly name if you want.
You are ready to use a custom font.
Now, rebuild your solution and use your custom font in the XAML or C# as you would normally use. In my MainPage I have one Label with the standard Hello World message from Xamarin.Forms project and I am using my Libre Baskerville in the FontFamily property of the Label control.
... and final result when I run my app it looks like this:
It's beautiful I know 😍... but at the end of the day, I have a custom font in my Xamarin.Forms app without too much work, just a few easy steps to follow and you are ready to go.
If you want to explore and read more about this I strongly recommend you to take a look at Xamarin dev blog post by my dear friend Gerald Versluis, you can find that post here.
You can also check out official docs about this and all other topics docs by Microsoft team, you can also find that here.
You can find project code (if you need it) on my GitHub profile here.
Hope this was helpful for you, if it was, please share it with your friend and colleagues.
Wish you lots of luck with coding! 👌