Search code examples
c#fontsmauiembedded-resource

MauiFont not imported in net7.0-windows10.0.19041.0 project


A .ttf file that is designated MauiFont resource seems to import automatically for an iOS or Android project. What would it take to import home.ttf manually in order to make Windows recognize the font?

In the Resources\Fonts folder of my Maui app, there is a home.ttf where the BuildAction is set to MauiFont. I want to initialize the icons for the flyout items by doing something like this, which works in Android and iOS, but not in Windows.

protected override void OnAppearing()
{
    base.OnAppearing();
    foreach (var name in Enum.GetNames(typeof(FlyoutText)))
    {
        var menuItem = new Microsoft.Maui.Controls.MenuItem { Text = name };

        menuItem.IconImageSource = new FontImageSource
        {
            FontFamily = "home",
            Glyph = "\uE800",
            Size = 75,
            Color = Colors.Black,
        };
        menuItem.Clicked += onFlyoutItemClicked;
        Shell.Current.Items.Add(menuItem);
    }
    Shell.Current.Items[0].IsVisible = false;
}

android shows icon glyph- windows shows not-found placeholder


With a FontFamily that is certain to be found, it can be demonstrated that the method works. What does Windows need to achieve the same objective of importing a custom font?

menuItem.IconImageSource = new FontImageSource
{
    FontFamily =  "Webdings",
    Glyph = "\u0048",
    Size = 75,
    Color = Colors.Black,
};

windows success


Solution

  • Make sure you register your font in MauiProgram.cs, i.e.

        public static class MauiProgram
        {
            public static MauiApp CreateMauiApp()
            {
                var builder = MauiApp.CreateBuilder();
                builder
                    .UseMauiApp<App>()
                    .ConfigureFonts(fonts =>
                    {
                        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                        fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                        fonts.AddFont("home.ttf", "home"); // <=  Add your font here
                    });
    
                builder.Services.AddLocalization();
    
    #if DEBUG
            builder.Logging.AddDebug();
    #endif
    
                return builder.Build();
            }
        }