Embedded Fonts - Xamarin.Forms
There are number of articles for custom fonts in Xamarin.Forms. With the new release of Xamarin forms 4.5.530, this can be done on the shared project. YES! that means no more platform-specific implementation of handling fonts and adding files in different Xamarin native projects. The new use of the embedded fonts reduces the implementation time drastically, this works with Font Icons (e.g: FontAwsome) or fonts (e.g: OpenSans-Bold). In this article I will show 3 simple steps on how easy it is to implement.
Prerequisite:
- Xamarin.Forms 4.5.530 or higher
Implementation:
1. Add font file
Add the (otf or ttf) file to the shared project set the Build Action to EmbeddedResource (see screenshot below).
2. Register Font
Registering your font can be done anywhere, However the most apparent place is the AssemblyInfo.cs or App.xamal.cs.
[assembly: ExportFont("FontAwesomePro-Regular.otf", Alias = "FontAwesomeRegular")]
3.Consume Font
CodeSnippet below is an example on how the font is used in image. I used Alias Property to name my font "FontAwsomeRegular" instead of using the actual filename. I also used Andrei Nitescu's IconFontToCode to create a C# class with constant fields for the icons.
<Image>
<Image.Source>
<FontImageSource
FontFamily="FontAwesomeRegular"
Glyph="{x:Static local:IconFont.CalendarTimes}"
Color="Blue"
Size="64" />
</Image.Source>
</Image>
Result:
Screenshot below show the app running with the new implementation:
Conclusion:
In conclusion the new method works great and it reduces the implementation time. No need to add font files on Android or iOS projects or even to add the file name to Info.plist. This is all handled by the shared projects. This helps when tweaking the project in the future as everything is in one place.
Hey man, seems like a pretty decent articles but just gave it a quick skimp for now, I couldn't really see what this does for me. Can you add a picture showing how it looks like with the custom font turned off?