Add custom fonts to Xamarin Forms quickly and easily
If you have ever added a font to Xamarin Forms, you know that the process is long and frustrating.
Thanks to a new feature added in Xamarin.Forms 4.6, it’s now extremely easy to add one or more fonts to your apps.
To show you how to do it, I’m going to add the probably most famous icon font package available around: FontAwesome! You can add all the fonts you want and the procedure is always the same and it’s the following:
Some fonts are very cool but FontAwesome is really awesome. You can use it to add thousands of icons to your apps for Android, iOS and all the other platforms supported by Xamarin.Forms. In this case I’m going to use the free version of this font.
First of all, go on their page and download the font:
Download the free desktop version and extract it. You’ll see that there are 3 otf files. Now simply copy these 3 files in your .netstandard project. I suggest you to create an Asset folder and copy these 3 files inside. The final result would be something like:
Remember to set the Build Action of these 3 files to Embedded Resource (Right click on the files, select Properties and then change the Build Action.
The next and almost final step, is to open the AssemblyInfo.cs file and add a line for each font just added:
[assembly: ExportFont("FontAwesome5Brands.otf", Alias = "FAB")]
[assembly: ExportFont("FontAwesome5Regular.otf", Alias = "FAR")]
[assembly: ExportFont("FontAwesome5Solid.otf", Alias = "FAS")]
I’ve also added an alias to make it even easier to use the fonts.
Now, to use a fontawesome icon in your labels, you need to use the code corresponding to that icon. Let’s say that you want to add the Android icon in your app:
As you see in the information on top of the image, this icon is in the Brand font and it’s code is f17b. So to add it to our app we simply add this to our XAML:
<Label FontFamily="FAB" Text="" TextColor="Green" />
The only things that we need are the FontFamily (FAB) and the icon code (f17b), then we can use every color and size we want.
It’s is also possible to replace strange codes with a single clean property. Discover how in this new useful tutorial
In really 2 minutes we are now able to add amazing fonts and icons to our apps.
As usual, if you like the article or have any questions or problems, leave a comment down here and I’ll reply as soon as possible!