It was just about 1 year ago when I wrote about using font icons for images inside of Xamarin.Forms apps. Well time has flown by and now more than ever is the time to go all in on custom fonts and font icons because with Xamarin.Forms 4.6 everything got so much easier!
See my full walkthrough:
So, let's start off with the basics when it comes to fonts. You usually think about fonts as just a fancy way to display text. However, with resources such as Font Awesome you can use fonts as icons instead of images. Font Awesome provides a plethora of free font icons and the actual files are small at about 400KB for all 3 free that you can download from this link here. You can put them in Tabs, Labels, and Images, and they are awesome!
Previously there was a lot of setup required, but with Xamarin.Forms 4.6 embedded fonts you can now drag them into your .NET Standard project in Visual Studio and mark them as an EmbeddedResource
:
Then all you need to do is head over to your AssemblyInfo.cs or App.xaml.cs and add this new fancy export code. You can even give the font an Alias to easily identify it later.
[assembly: ExportFont("CustomFont.ttf", Alias = "AnimalCrossing")]
[assembly: ExportFont("fa-regular-400.ttf", Alias = "FA-R")]
[assembly: ExportFont("fa-solid-900.ttf", Alias = "FA-S")]
[assembly: ExportFont("fa-brands-400.ttf", Alias = "FA-B")]
When you head over to the font awesome website each icon will have a specific unicode associated with it:
We can now put these in our Application Resources that we can call on later:
<x:String x:Key="IconCoffee"></x:String>
Now, we can use it in our fancy Shell Tabs (or Image) like you saw earlier using FontImageSource
:
<Tab Title="Profile" Route="profile">
<Tab.Icon>
<FontImageSource Glyph="{StaticResource IconCoffee}" FontFamily="FA-S" />
</Tab.Icon>
<ShellContent ContentTemplate="{DataTemplate view:ProfilePage}"/>
</Tab>
We can also use them in a Label:
<Label
FontFamily="FA-S"
Style="{StaticResource SocialLabel}"
Text="{StaticResource IconCoffee}" />
If you are referencing your Icons from C# you can generate a full schema from the font by using this awesome site IconFont2Code. Or if you want a pre-generated on checkout Matthew Robin's GitHub fa2cs project that has a pre-made file to do this. Once you add the file you can then have access to every icon!
You can use an icon in XAML by:
- Adding a namespace reference to
FontAwesome
:xmlns:fontAwesome="clr-namespace:FontAwesome"
; - Referencing a icon using
x:Static
:<Label Text="{x:Static fontAwesome:FontAwesomeIcons.Alicorn}"/>
- or in code
submitButton.Text = FontAwesome.FontAwesomeIcons.Check;
Now, go off and use those custom fonts! Want more, read through the docs.