Tuesday, September 29, 2015

FontAwesome using Xamarin Forms and Android

FontAwesome is, well, awesome... And be warned, this is kind of a hack.

EDIT: Here's the iOS version, but please read this post first anyhow.

On Android, it's a bit of a hassle use FontAwesome. This blog post is about how to use Font Awesome in the simplest way possible. It's as easy as using a Label once set up.

The hack is simple. We use a custom renderer that looks at the Label in question, determines if there is one character in the text field and if that character has the value of 0xf000 or higher. If so, we replace the font with FontAwesome.

Since the icons all begin at 0xf000 or higher, the custom renderer will make sure that the correct font is used.

The first label in the example below will simply print out the text. The second label will show a map marker icon using a single unicode character and the third references a local static object that maps all the icons to a friendly name. The static object is in the sample project.

            <!-- Business as usual -->
            <Label Text="Just Normal Text" />

            <!-- A Map marker using a single character -->
            <Label Text="&#xf041;" FontSize="40" />

            <!-- Using a resource -->
            <Label Text="{x:Static local:FontAwesome.FAPhone}" FontSize="40" />

This will result in the following screen.

Here's how you do it.

Download the font

Download the FontAwesome font and drop it in your Asset folder for the Droid project. Don't forget to check that the build type is set to AndroidAsset.

Create a custom renderer

The magic goes here. In the Droid project, create a custom renderer that looks like this.

[assembly: ExportRenderer(typeof(Label), typeof(AwesomeRenderer))]

namespace Awesome.Droid
    public class AwesomeRenderer : LabelRenderer
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)

            var label = (TextView)Control;

            var text = label.Text;
            if(text.Length > 1 || text[0] < 0xf000)

            var font = Typeface.CreateFromAsset(Xamarin.Forms.Forms.Context.ApplicationContext.Assets, "fontawesome.ttf");
            label.Typeface = font;