(616) 371-1037

[email protected]

Simple way to use icon fonts in Xamarin Forms projects

December 7, 2018 - Valeriy Kovalenko

1 Comment

Almost all apps use some kind of graphic icons to make the UI more attractive and easy to use. Here I will demonstrate a quick way of adding icon fonts in Xamarin applications.

There are plenty of icon sets available as web fonts for free, e.g. FontAwesome, Material Icons, Icofont. But, as mobile devs, we should always be concerned about the app size. For this example, I will use a handy service to create a custom font that only contains the icons I need: Fontello.
To create a custom font:
  1. Select icons that you’re interested in or upload an SVG;
  2. Write down the icons codes, we’ll need them later;
  3. Set a font name and hit the download button.

OK, now we have everything ready to add these icons to the app. Open your Xamarin Forms project in Visual Studio and let’s start with adding the .ttf file to the native projects.

Android

Add the file to the Assets folder and make sure that the Build Action is AndroidAsset (should be set by default).

iOS

Add the file to the Resources folder, make sure that the Build Action is BundleResource (again, should be set by default).
In iOS projects, we also need to list custom fonts in the Info.plist file. There are two ways to do that: double-click on the Info.plist file, select the Source tab and add a ‘Fonts provided by application‘ record (don’t forget to replace customfont.ttf with your font name):
Or if you prefer to edit the Info.plist in a text editor, just add the following lines before the closing </dict>  tag:

Xamarin Forms Project

At this point, we have everything ready to use the icons in the app. Let’s add a new item to the ResourceDictionary in the App.xaml to handle platform specific differences:

And finally the icons. Add a label to a page, set the FontFamily and the Text properties:

Notice that we’re using the codes that we wrote down from the Fontello service here. To make the XAML code a bit cleaner we can move all properties to a style and set only the icon code (Text property) in the label. Or even create separate styles for all frequently used icons:

It’s also possible to update the text programmatically from the code-behind or via bindings from the view model. E.g. when you want to show an arrow indicating the sort order:

And finally a nice bonus — since this is just a label with some text (or any other control with a text), you can easily change the color, size or even add an animation. You can find a sample project here: https://github.com/vecalion/Xamarin.IconFontDemo

Happy coding!

Valeriy Kovalenko

One thought on “Simple way to use icon fonts in Xamarin Forms projects

Leave a comment

Your email address will not be published. Required fields are marked *