4

I'm following the Fonts Tutorial proposed by Xamarin to have a custom downloaded fonts over each plateform. However, I got lot of problems and I also try to find a way to do some things but whitout find how to make it works.

First, take a look at the tutorial and begin at the concerning part. Using a Custom Font


iOS:

It says that we have to add the font.tff into the Resources folder. Then, we have to do something with the Info.plist, but what? I'm not sure to understand what I have to do.

Androïd:

Xamarin.Forms for Android does not currently expose the ability to set the font to a custom font file, so custom renderers are required.

CustomLabelRenderer.cs

public class CustomLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        System.Diagnostics.Debug.WriteLine(Forms.Context.ApplicationContext.Assets, e.NewElement.StyleId + ".ttf");

        if (!string.IsNullOrEmpty(e.NewElement?.StyleId))
        {
            var font = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, e.NewElement.StyleId + ".ttf");
            Control.Typeface = font;
        }
    }
}

According to the documentation, the OnElementChanged() would be called, however, it doesn't. Debug.WriteLine() doesn't display anything. Why?

WinPhone 8.1:

We have to add the font file to the /Assets/Fonts/ folder in the application project and set the Build Action:Content. Once realized, Xamarin.Forms for Windows Phone can reference a custom font that has been added to the project by following a specific naming standard. However, the Font doesn't take place on the view, the font stays standard, why?


At the moment, after lot of searches, lot of try... Nothing..

I'm trying to add DIN Condensed Bold font

My XAML layout:

<ContentPage.Content>
 <AbsoluteLayout BackgroundColor="#235A5E">
  <!-- Menu -->
  <AbsoluteLayout x:Name="Menu" BackgroundColor="#2F767B"
                  AbsoluteLayout.LayoutBounds="0,0,1,0.1"
                  AbsoluteLayout.LayoutFlags="All">
    <Label x:Name="label" Text="Connection" TextColor="White" FontSize="30" VerticalOptions="Center" HorizontalOptions="Center"
           AbsoluteLayout.LayoutBounds="0.5, 0, 0.8, 1"
           AbsoluteLayout.LayoutFlags="All"/>
    <Button x:Name="ConnectionButton" BackgroundColor="Transparent" BorderColor="Transparent"
           AbsoluteLayout.LayoutBounds="1, 0.5, 0.2, 1"
           AbsoluteLayout.LayoutFlags="All"/>
  </AbsoluteLayout>
 </AbsoluteLayout>
</ContentPage.Content>

So the FontFamily property of the Label can be set like that

<Label Text="Hello World !" FontFamily="DIN Condensed Bold"

But, as told in the tutorial, for the WinPhone by example, it has to be done by another way so, I try to change the FontFamily by the C# part.

public partial class MyPage : ContentPage
{
    public string FontFamily { get; set; }

    public MyPage()
    {
        InitializeComponent();

        label.FontFamily = Device.OnPlatform(
            iOS: "DIN Condensed Bold",
            Android: "DIN Condensed Bold",
            WinPhone: @"Assets\Fonts\DINCondensedBold.ttf#DIN Condensed Bold"
        );
    }
}

Which doesn't works too ! I also saw something interesting for me about the XAML part. I want (f the FontFamily works one day..) to have a defintion we makes me able to just edit one field string to set all Label's FontFamily of my page.

<ContentPage.Resources>
  <ResourceDictionary>

  </ResourceDictionary>
</ContentPage.Resources>

I saw that I might be able to define a FontFamily for all of the Label of MyPage.xaml, how does it works?

I'm also a newbie about MVVM but I tried to bind my public string FontFamily { get; set; } to the Label defined in the xaml <Label Text="Hello World !" FontFamily="{Binding FontFamily}"/> but one more time, without success..

I'm totaly stuck... Who can help either to make works the tutorial or explain me each things I mentioned after the tutorial. Thank for help !

6
  • 1
    read the blog entry linked from that Guide, it has a more detailed description of modifying the info.plist
    – Jason
    Jun 13, 2016 at 20:25
  • You might also try tackling this one platform at a time - as it is you have multiple questions packed into a single post, which is difficult to answer concisely
    – Jason
    Jun 13, 2016 at 20:27
  • 1
    Thank for your answer. Ok so for the others (Android/WinPhone) why it doesn't works? I just want to make a question/answer usefull for peoples who got the same issues
    – Emixam23
    Jun 13, 2016 at 23:12
  • 1
    I have had similar problems double check the file name and font name are the same, also the font names are case sensitive. Jun 14, 2016 at 4:57
  • Thank ;) Now it works for Android but no WinPhone 8.1...
    – Emixam23
    Jun 14, 2016 at 10:14

3 Answers 3

19

I think at some point the Xamarin Forms approach to this got easier than even needing a Custom Renderer (or an Effect etc.). First, there's the official guidance: https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/#Using_a_Custom_Font.

The working solution for iOS, Android, and UWP, for me ended up being this:

    <Label Text="The sly fox jumps over the lazy brown dog.">
        <Label.FontFamily>
            <OnPlatform x:TypeArguments="x:String">
                <On Platform="iOS" Value="OpenSans-Semibold"/>
                <On Platform="Android" Value="Fonts/OpenSans-Semibold.ttf#OpenSans-Semibold"/>
                <On Platform="UWP" Value="Assets\Fonts\OpenSans-Semibold.ttf#Open Sans"/>
            </OnPlatform>
        </Label.FontFamily>
    </Label>

For all three platforms the font files in this example are stored in a Fonts subfolder. You see that reflected in the Android and UWP (WinPhone) path above. In iOS the plist entries hold the path info to the custom font.

The hardest part was figuring out the font names / preferred font. Notice the differences after the "#" for Android and UWP/WinPhone. Combination of trial and error (Android) and thanks to this article for helping to point out the specificity needed: http://www.blendrocks.com/code-blend/2015/01/04/a-complete-guide-to-working-with-custom-fonts-in-your-windows-and-windows-phone-app.

The most relevant part of that article being how picky and not obvious the preferred font name can be. The Windows font viewer (and the Mac Font Book too, btw, afaik) do not show you the preferred family name. From the article:

This part "#Helvetica Neue LT Std" is a suffix containing the Preferred Family. It's required in order for the custom font to work. The suffix has to be absolutely correct and it's case sensitive.

  • The easiest way to find it is to use a tool called dp4 font viewer. It's free and can be found downloaded here. Find your font through the program, go to the info tap copy the Preferred Family.
  • Do NOT use Windows built in font viewer as it does NOT show the correct preferred font family.

EDIT: Updated the OnPlatform snippet to current recommended syntax.

EDIT2: Changed WinPhone platform to UWP and removed leading backslash '\' for the UWP path - didn't realize that wasn't working on UWP/WinPhone! Also fixed download link for dp4 Font Viewer as it requires 'https' now.

1

2020 Update, Xamarin.Forms 4.5 supports custom fonts embedded in one place (shared UI project) and exported via ExportFont attribute: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/fonts#use-a-custom-font - works for iOS, Android and UWP. For macOS and WPF you still have to embed fonts in each platform project as described below.

  1. Download TTF files and and bundle them as resources with each platform project
  2. Reference the fonts from within Xamarin.Forms shared project, taking into account the peculiarities of each platform (naming conventions for addressing resources and font families).
  3. Apply the fonts to Xamarin.Forms controls.

Here's detailed description on how to add and apply custom fonts in macOS, WPF and Android.

1
0

As of Xamarin.Forms 4.5.530 and up, there is no need to specify platform, nor add font files to each native project (Android, iOS and UWP). Strongly recommend Xamarin devblogs article as a guide.

My approach: add a custom font file, fx. OpenSans-Regular.ttf, to a new folder within the shared code project. Add [assembly: ExportFont("OpenSans-Regular.ttf", Alias = "OpenSans")] and the namespace reference using Xamarin.Forms; to the AssemblyInfo.cs file within the shared code project. Then reference the Alias name from a control within a .xaml file like so <Label Text="Username" FontFamily="OpenSans" />.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.