martes, 12 de febrero de 2019

Using Font Awesome in Xamarin.Forms

All the code for this post is available at github

If you want to have a consistent user interface in your Xamarin Forms application, it could be a good approach to try to use vector icons.

For that, I will show you in this blog post, how you can include Font Awesome in your Xamarin Forms project to show icons like in this sample.


First you will need to download the icons from the Font Awesome site (in this post we are using the free web version 5.7.1).

Select the Start Using Free button.

And then the download button.

After downloading, extract the content of your zip file.

And copy the highlighted file to your Android's Assets folder and iOS's Resources folder.

Change the properties in both to match the images.

For iOS you need to change the info.plist file and include the new font file.

Create support classes

After the installation is complete, we are going to create a derived class from Label to show our text using Font Awesome.

The class is called FontAwesomeIcon in our sample project.

For Android that class needs a renderer (FontAwesomeIconRenderer.cs).

The icon definitions are in the Icon.cs file, you could add any other icon that you need looking for the icon in this link  and using the unicode representation.

Using our custom label to show icons

To show an icon in a view with xaml, create a tag like the three that we have in MainPage.xaml, setting the text to one of our defined icons in the Icon class.

And that's all you need to start using Font Awesome!!

Pro tip

You could have noticed that the name of the font used in the FontAwesomeIcon.cs file depends on the platform, the android version is just the name of the ttf file, but for iOS we need the name of the font. In some tutorials they mention that you could check the properties of the file in Windows Explorer and take the name from there, but for the FontAwesome version that we are using for this post, that's not true.

You can see the name of the font in the console of Visual Studio when you run the iOS version because we have this code in place (AppDelegate.cs).

This will be very useful if you want to use another version of the font, but you don't know the name.

1 comentario: