FontImageSource is a new way to use web fonts to render common images such as action buttons in your app. Before this was added into the platform in version Xamarin.Forms 3.6 you would have to create resources for each platfrom and treat it as an image. Now in Xamarin.Forms version 4.2 there is a brand new Markup Extension to simplify your XAML.
This is an exciting new feature to the platform that I made while working on a project earlier this year. You can see all the details at the official PR Xamarin/Xamarin.Forms#6398
Using FontImageSource
To use the FontImageSource
you add the custom font for iOS and/or Android. Once included you can use all the benefits of the XAML nesting to specify what specific font to use. Consider the following MainPage.xaml
where we specify an ImageButton
.
MainPage.xaml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="App1.MainPage">
<StackLayout>
<ImageButton Source="MyImage" />
</StackLayout>
</ContentPage>
Instead of specifying the Source
to reference an image asset, update the markup XAML to use the new FontImageSource
.
1
2
3
4
5
6
7
8
<ImageButton>
<ImageButton.Source>
<FontImageSource FontFamily="MyFontFamily"
Glyph="Plus"
Color="Red"
Size="75" />
</ImageButton.Source>
</ImageButton>
New Markup Extension
What is a Markup Extension?
In XAML there is a special syntax that allows the code to perform additional rules and indirectly set other objects. See the official Microsoft Docs on Markup Extensions.
One of the most common Markup Extensions that you probably use every day in MVVM development in Xamarin.Forms is binding. Suppose you have a Label
that you want to render the text from a ViewModel
that has a Message
property.
ViewModel
1
2
3
4
public class MyViewModel
{
public string Message { get; set; }
}
View (Snippet)
1
<Label Text="{Binding Message}" />
FontImageSource Markup Extension
The code from earlier can now be simplified in the new Markup Extension.
1
2
3
4
5
<ImageButton Source="{FontImage
FontFamily={StaticResource MyFontFamily},
Glyph={StaticResource SmileFace},
Color={StaticResource White},
Size=75}" />
Yes! It really is that simple.
More Goodies in 4.2
There are more new features and goodies that were released in Xamarin.Forms 4.2. Checkout the blog from the Xamarin Team
-Happy Coding