Implement Custom Fonts Using Effects In Xamarin Forms

Recently I had a requirement to use custom fonts (a font other than one present in a device) in one of my Xamarin forms apps, so I looked for the same in Xamarin documentation and found that the example is using Custom render to implement the same in Android apps. This would have been fine before Xamarin Forms 2.3 was released, but now we have an awesome feature called Effects to implement these kind of small platform specific customizations, so that we don’t need to create a new custom control for every small platform specific change needed in the control. This article will show how to implement custom fonts in Android iOS & UWP apps using effects.

So first create a new project in Xamarin/Visual Studio then perform the changes/additions mentioned in following sections.

Changes in PCL project

  1. Create a new class file named ‘CustomFontEffect’ and add the following code to it,
    1. public static class CustomFontEffect  
    2. {  
    3.     public static readonly BindableProperty FontFileNameProperty = BindableProperty.CreateAttached("FontFileName"typeof(string), typeof(CustomFontEffect), "", propertyChanged: OnFileNameChanged);  
    4.     public static string GetFontFileName(BindableObject view) {  
    5.         return (string) view.GetValue(FontFileNameProperty);  
    6.     }  
    7.     public static void SetFontFileName(BindableObject view, string value) {  
    8.         view.SetValue(FontFileNameProperty, value);  
    9.     }  
    10.     static void OnFileNameChanged(BindableObject bindable, object oldValue, object newValue) {  
    11.         var view = bindable as View;  
    12.         if (view == null) {  
    13.             return;  
    14.         }  
    15.         view.Effects.Add(new FontEffect());  
    16.     }  
    17.     class FontEffect: RoutingEffect {  
    18.         public FontEffect(): base("Xamarin.FontEffect") {}  
    19.     }  
    20. }  
  2. In the above mentioned code we are creating a custom effect where we are creating a new property named ‘FontFileName’ for the Bindable object to which the effect will be attached. The implementation of this effect will have to be written in Platform specific projects.

  3. In order to implement custom fonts using XAML, set the ‘FontFamily’ of label per the following XAML code,
    1. <Label Text="This custom font 'AbeatByKai' (First in selection picker) is Set in XAML as an Example, This will not change. " local:CustomFontEffect.FontFileName="abeatbyKaiRegular">  
    2. <Label.FontFamily>  
    3. <OnPlatform x:TypeArguments="x:String">  
    4. <OnPlatform.iOS>AbeatByKai</OnPlatform.iOS>  
    5. <OnPlatform.Android></OnPlatform.Android>  
    6. <OnPlatform.WinPhone>/Assets/Fonts/abeatbyKaiRegular.ttf#AbeatByKai</OnPlatform.WinPhone>  
    7. </OnPlatform>  
    8. </Label.FontFamily>  
    9. </Label>  
  4. No font name is provided for Android platforms as it requires the name of the font file without extension to create the font in platform specific code, that name we are passing in the new property ‘FontFileName’ which is attached while attaching the effect to the control (codelocal:CustomFontEffect.FontFileName=”abeatbyKaiRegular” ).

    The font name to be used in iOS & UWP/WinPhone (after #) can be taken out from the font file by opening it in font installer as highlighted in following screenshot.

    print

  5. In order to implement custom fonts in code behind use the following C# code,
    1. Device.OnPlatform(iOS: () =>  
    2. {  
    3.     lblSample.FontFamily = "AbeatByKai";  
    4. }, Android: () => {  
    5.     CustomFontEffect.SetFontFileName(lblSample, "abeatbyKaiRegular");  
    6. }, WinPhone: () => {  
    7.     lblItalics.FontFamily = "/Assets/Fonts/abeatbyKaiRegular.ttf#AbeatByKai";  
    8. });  

Changes in iOS project

Implementation of custom fonts in iOS is pretty straitforward, so just mentioning about the same for the sake of documentation,

  • Copy the the custom fonts you need to use in ‘Resources’ folder in iOS specific project as shown in the below screenshot (I kept the file in a separate folder; for the sake of clarity you can put them directly in ‘Resources’ folder also if you want)

    font

  • Change the ‘Build Action’ property of every font file as ‘BundleResource’ and ‘Copy to output directory’ to ‘always copy’,

    Build Action

  • Open the ‘info.plist’ file in XML editor by right clicking on it and selecting ‘Open With’ option and then selecting XML (Text) Editor from the list of editors given as shown in the below screenshots,

    XML

  • Add new XML key element ‘UIAppFonts’ and list your custom fonts in array in ‘info.plist’ as per the following screenshot.

    XML

That’s it --  your iOS application is ready for showing the custom fonts; no effect implementation is needed for this project.

Changes in Android project

Android project is the main one for which we are writing this blog,

  1. Copy the the custom fonts you need to use in ‘Assets’ folder in Android specific projects as shown in the below screenshot (I kept the file in a separate folder; for the sake of clarity you can put them directly in ‘Assets’ folder also if you want)

    Assets

  2. Change the ‘Build Action’ property of every font file as ‘AndroidAsset’ and ‘Copy to output directory’ to ‘Copy Always’,

    Build Action

  3. And finally write the implementation for the effect which we have declared in PCL project, for that add a new class file named ‘FontEffect.cs’ to the project and update it with the following code:
    1. using System;  
    2. using CustomFontEx.Droid;  
    3. using Xamarin.Forms;  
    4. using Xamarin.Forms.Platform.Android;  
    5. using Android.Widget;  
    6. using Android.Graphics;  
    7. using System.ComponentModel;  
    8. [assembly: ResolutionGroupName("Xamarin")]  
    9. [assembly: ExportEffect(typeof(FontEffect), "FontEffect")]  
    10. namespace CustomFontEx.Droid {  
    11.     public class FontEffect: PlatformEffect  
    12.     {  
    13.         TextView control;  
    14.         protected override void OnAttached() {  
    15.             try {  
    16.                 control = Control as TextView;  
    17.                 Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Fonts/" + CustomFontEffect.GetFontFileName(Element) + ".ttf");  
    18.                 control.Typeface = font;  
    19.             } catch (Exception ex) {  
    20.                 Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);  
    21.             }  
    22.         }  
    23.         protected override void OnDetached() {}  
    24.         protected override void OnElementPropertyChanged(PropertyChangedEventArgs args) {  
    25.             if (args.PropertyName == CustomFontEffect.FontFileNameProperty.PropertyName) {  
    26.                 Typeface font = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, "Fonts/" + CustomFontEffect.GetFontFileName(Element) + ".ttf");  
    27.                 control.Typeface = font;  
    28.             }  
    29.         }  
    30.     }  
    31. }  

Changes in UWP project

Implementation of custom fonts in UWP is easier  & more  straitforward than in iOS, so just mentioning about the same for the sake of documentation,

  • Copy the the custom fonts you need to use in ‘Assets’ folder in UWP specific project as shown in below screenshot (I kept the file in a separate folder; for the sake of clarity you can put them directly in ‘Assets’ folder also if you want),

    Assets

  • Change the ‘Build Action’ property of every font file as ‘Content’ and ‘Copy to output directory’ to ‘Copy if newer’,

    Build Action

That’s it  -- your UWP application is ready for showing the custom fonts, no effect implementation needed for this project.

This is how the sample application whose code is published on Github looks on executing.

iOS Simulator

iOS Simulator

Android Simulator

Android Simulator

Windows 10 Simulator

Windows 10 Simulator

Let me know if I have missed anything orif you have any suggestions/concerns/queries.

Up Next
    Ebook Download
    View all
    Learn
    View all