Adding Font Awesome to .NET MAUI App
First, download the desktop version of the Font Awesome fonts.
https://fontawesome.com/download
Extract the .OTF files to the project's Resources/Fonts folder. You can rename the files to something easier to type/read, if desired. After copying, check the properties on the files and make sure the Build Action = "MauiFont".
Open the MauiProgram.cs file and add the new fonts to the app builder.
{
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("FontAwesome6Brands.otf", "FontAwesomeBrands");
fonts.AddFont("FontAwesome6Regular.otf", "FontAwesomeRegular");
fonts.AddFont("FontAwesome6Solid.otf", "FontAwesomeSolid");
});
return builder.Build();
}
}
A helpful task is creating a class that maps the icon glyphs to something easier to read. You can either manually create one, or use a tool to generate one. https://andreinitescu.github.io/IconFont2Code/ is a live tool that will convert on the fly, but it didn't work for me, so I downloaded a pre-generated class from https://github.com/matthewrdev/fa2cs
In the page XAML, add a namespace reference for your mapping class.
xmlns:coreModels="clr-namespace:Core.Models;assembly=Core"
To use Font Awesome icons in the ContentPage ToolbarItems:
<ToolbarItem
<ToolbarItem.IconImageSource>
<FontImageSource
FontFamily="FontAwesomeSolid"
Glyph="{x:Static coreModels:FontAwesomeIcons.FloppyDisk}"/>
</ToolbarItem.IconImageSource>
</ToolbarItem>
</ContentPage.ToolbarItems>
To use Font Awesome in an element like Label:
Text="{x:Static coreModels:FontAwesomeIcons.FloppyDisk}"
I know this a very old article but I'm really struggling to work out to how use the icons from FontAwesome in my MAUI pages. The first issue is adding the coreModels reference - VS 2022 just says Assembly 'Core' was not found. Is this an assembly of some sort we need to add?
ReplyDeleteAlso in current MAUI projects the AwesomeFonts are all .ttf not .otf - so again, has something changed?
Is there any way you could update this for current MAUI projects (as at April 2024)? I need to use a few icons from it and I can't find any resources that show me how to use it in XAML.
OK, don't worry - workerd it out. For anyone else that finds this, here's how I did it:
ReplyDeleteI had to add a reference as follows:
xmlns:fonts="clr-namespace:MyTestApp.App.Resources.Styles"