Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 107 additions & 50 deletions docs/guides/styles-and-resources/how-to-use-fonts.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,31 @@ id: how-to-use-fonts
title: How To Use Custom Fonts
---

Customizing your Avalonia application with unique fonts can add a distinctive look and feel. This guide will walk you through the process of integrating custom fonts into your Avalonia application.
Customizing your Avalonia application with unique fonts can add a distinctive look and feel. This guide explains how to integrate custom fonts into your Avalonia application.

<GitHubSampleLink title="Google Fonts" link="https://github.com/AvaloniaUI/AvaloniaUI.QuickGuides/tree/main/GoogleFonts"/>
## Using a custom font as a static resource

## Add Your Custom Font to the Project
### Clone the Google Fonts sample

Before you can use a custom font, you need to include it in your project.
Start by cloning our [Google Fonts sample project](https://github.com/AvaloniaUI/AvaloniaUI.QuickGuides/tree/main/GoogleFonts). This project includes files for the [Nunito](https://fonts.google.com/specimen/Nunito) font, which we will be using throughout this guide.

In this guide, we will be using a font called [Nunito](https://fonts.google.com/specimen/Nunito) which is already stored in our application resources under `avares://GoogleFonts/Assets/Fonts`.
### Add your custom font to the project

Ensure that the fonts have the build property set to `AvaloniaResource`.
Before you can use a custom font, you must include it in your project.

## Declare Your Font in Application Resources
Open **GoogleFonts.csproj** in the sample project you cloned. You can see that the `Assets` directory has already been set as an `AvaloniaResource`. This ensures that fonts in the directory are correctly built at runtime.

In your Avalonia application, open your `App.xaml` file and include your custom font inside `<Application.Resources>`. Assign it a key, which you will use to reference it in your application. In this case, we have assigned the key `NunitoFont`.
Resources in this directory can be accessed through `avares://GoogleFonts/Assets/Fonts`.

```xml title="GoogleFonts.csproj"
<AvaloniaResource Include="Assets\**" />
```

### Declare your font in application resources

1. In your Avalonia application, open `App.axaml`.
2. Include your custom font inside the `<Application.Resources>` tag.
3. Assign it a key to use as reference in your application. In this case, we have assigned the key `NunitoFont`.

```xml title="App.axaml"
<Application xmlns="https://github.com/avaloniaui"
Expand All @@ -27,20 +37,21 @@ In your Avalonia application, open your `App.xaml` file and include your custom
<Application.Styles>
<FluentTheme />
</Application.Styles>
// highlight-start
// highlight-start
<Application.Resources>
<FontFamily x:Key="NunitoFont">avares://GoogleFonts/Assets/Fonts#Nunito</FontFamily>
</Application.Resources>
// highlight-end
// highlight-end
</Application>
```

## Use Your Custom Font
Once your font is declared in your application resources, you can use it in your application.
### Apply your custom font

To reference your custom font, use the `FontFamily` attribute with the `StaticResource` markup extension. You need to pass the key of the declared font as the parameter. In this case, `NunitoFont` is the key for our custom font.
Once your font is declared in the application resources, you can use it in your application.

Here's an example of how to apply our custom `Nunito` font to a `TextBlock`:
To reference your custom font, use the `FontFamily` attribute with the `StaticResource` markup extension. Pass the key of the declared font as the parameter, which in this case is `NunitoFont`.

In the below example, the text displayed in the `TextBlock` control is now size 70, and uses the Nunito font.

```xml
<TextBlock Text="{Binding Greeting}"
Expand All @@ -49,73 +60,119 @@ Here's an example of how to apply our custom `Nunito` font to a `TextBlock`:
HorizontalAlignment="Center" VerticalAlignment="Center"/>
```

In the above example, the `TextBlock` control will use the `Nunito` font that we declared in our application resources. The text bound to the `TextBlock` will now appear in the `Nunito` font at the specified font size of 70.
The `FontFamily` attribute can be applied to any control with the `FontFamily` property, meaning you can use your custom font throughout your application.

---

Remember that the `FontFamily` attribute can be applied to any control that has the `FontFamily` property, meaning you can use your custom font throughout your application.
## Creating an embedded font collection

And that's it! You've successfully integrated a custom font into your Avalonia application. Now you can add a unique touch to your application's UI with the fonts of your choice.
### About embedded font collections

## Adding a Font to the Font Collection
`EmbeddedFontCollection` provides a way to add fonts to your application as a collection, so that you can use them without a reference to a static resource.

The `EmbeddedFontCollection` provides an easy way to add fonts to your application's collection of fonts without requiring a reference to a resource when using them. For example, instead of setting the `FontFamily` to `{StaticResource NunitoFont}`, you can simply reference the name of the font family directly.
For example, instead of setting the font family to `{StaticResource NunitoFont}`, as described in the previous section, you can reference the font family as `#Nunito`.

```xml
<TextBlock
Text="{Binding Greeting}"
FontSize="70"
FontFamily="Nunito"
// highlight-start
FontFamily="fonts:MyFonts#Nunito"
// highlight-end
HorizontalAlignment="Center" VerticalAlignment="Center" />
```

This requires additional setup on application construction, but it removes the need to remember a unique resource key when authoring your controls.
This requires additional setup, but removes the need to use a unique resource key when authoring your controls.

### Defining a Font Collection
### Defining a font collection

First, we need to define a collection of fonts by specifying the font family name and the directory in which the font files reside.
These instructions continue with the [Google Fonts sample project](https://github.com/AvaloniaUI/AvaloniaUI.QuickGuides/tree/main/GoogleFonts) you used in the [previous section](#using-a-custom-font-as-a-static-resource).

```csharp title="InterFontCollection.cs"
public sealed class InterFontCollection : EmbeddedFontCollection
1. (Optional) In the **App.axaml** file, delete the `NunitoFont` application resource. It is no longer needed. ~~`<FontFamily x:Key="NunitoFont">avares://GoogleFonts/Assets/Fonts#Nunito</FontFamily>`~~
2. Open the **Program.cs** file.
3. At the top of the file, add the declaration `using Avalonia.Media.Fonts;`

```csharp
using Avalonia;
using System;
// highlight-start
using Avalonia.Media.Fonts;
// highlight-end
```

4. Above the `Program` class, add a new class to create the `EmbeddedFontCollection`. In this example, we have named it `MyFontCollection`.

```csharp
public sealed class MyFontCollection : EmbeddedFontCollection
{
public InterFontCollection() : base(
new Uri("fonts:Inter", UriKind.Absolute),
new Uri("avares://Avalonia.Fonts.Inter/Assets", UriKind.Absolute))
public MyFontCollection() : base(
new Uri("fonts:MyFonts", UriKind.Absolute),
new Uri("avares://GoogleFonts/Assets/Fonts", UriKind.Absolute))
{
}
}
```

Here, `Inter` is the name of the font family and `avares://Avalonia.Fonts.Inter/Assets` is the resource locator for the directory containing the font files. The actual names of the font files are not significant since the `EmbeddedFontCollection` will search every file in the given directory and only load those fonts with the given font family name.
This class acts as a resource locator for the directory containing the custom font files. Here, the directory is `avares://GoogleFonts/Assets/Fonts`, and it is accessed with the key `fonts:MyFonts`.

For more information on how to create a resource locator, see [Assets](/docs/basics/user-interface/assets) for a primer on including assets in your project.
For more information on how to create a resource locator, see [Assets](/docs/basics/user-interface/assets).

### Adding the Font Collection
### Adding the font collection to the app

Next, we need to add this font collection to the application. This can be done by using `AppBuilder.ConfigureFonts` to configure the `FontManager` to include your fonts on application construction.
Next, we need to add `MyFontCollection` to the application.

1. Continue working in the file **Program.cs**.
2. Within the Avalonia configuration code, i.e. the code portion starting `public static AppBuilder BuildAvaloniaApp()`, use `AppBuilder.ConfigureFonts` to configure a font manager that includes the font collection when the app is constructed.

Your `class Program` should now look something like this:

```csharp title="Program.cs"
public static class Program
{
[STAThread]
public static void Main(string[] args) =>
BuildAvaloniaApp()
class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);

public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.ConfigureFonts(fontManager =>
{
fontManager.AddFontCollection(new MyFontCollection());
})
.LogToTrace();
}
```

### Applying a font from the font collection

1. Open the file **MainWindow.axaml**.
2. Update the `FontFamily` attribute of the `TextBlock` to use `FontFamily="fonts:MyFonts#Nunito"`.

```xml title="MainWindow.axaml"
<TextBlock Text="{Binding Greeting}"
FontSize="70"
// highlight-start
.ConfigureFonts(fontManager =>
{
fontManager.AddFontCollection(new InterFontCollection());
})
FontFamily="fonts:MyFonts#Nunito"
// highlight-end
.LogToTrace();
}
HorizontalAlignment="Center" VerticalAlignment="Center"/>
```

### Creating Font Packages
3. Build and run the app. Confirm the text is displayed in Nunito font.

The `FontFamily` value `fonts:MyFonts#Nunito` acts as a URI for the font file resource in your **Assets** folder. Its format is `{scheme}:{collection-key}#{font-family-name}`. In this case, the directory indicated by `fonts:MyFonts` is `/GoogleFonts/Assets/Fonts`, and the target font family, as marked by the `#` symbol, is `Nunito`.

`EmbeddedFontCollection` searches every file in the specified directory and loads files with the target font family name.

Your font collection can contain many font families and font files. To switch to another font within the **Assets** folder, change the `FontFamily` value to the desired font, e.g. `fonts:MyFonts#ComicSans`.

---

## Pre-built font packages

The [`Avalonia.Fonts.Inter`](https://github.com/AvaloniaUI/Avalonia/tree/master/src/Avalonia.Fonts.Inter) package is an example of a pre-built font package that contains fonts you can utilize across multiple projects. The fonts in the package can be accessed with a single method call in your app configuration file.

The [`Avalonia.Fonts.Inter`](https://github.com/AvaloniaUI/Avalonia/tree/master/src/Avalonia.Fonts.Inter) package shows how you can create a separate project to contain one or many fonts that you might use in multiple projects. Once you have created and published a project similar to this, using the font becomes as simple as appending a method call to your application construction.
If you wish to use the Inter font as included in the `Avalonia.Fonts.Inter` NuGet package, you can install the package and add `.WithInterFont()` to your Avalonia configuration code.

```csharp title="Program.cs"
public static class Program
Expand All @@ -135,6 +192,6 @@ public static class Program
}
```

## Which Fonts Are Supported?
## Which fonts are supported?

Most TrueType (`.ttf`) and OpenType (`.otf`, `.ttf`) fonts are supported. However, some font features, such as "Variable fonts" are not currently supported (see: [Issue #11092](https://github.com/AvaloniaUI/Avalonia/issues/11092)).
Most TrueType (`.ttf`) and OpenType (`.otf`, `.ttf`) fonts are supported. However, some font features, such as "Variable fonts" are not currently supported (See [Issue #11092](https://github.com/AvaloniaUI/Avalonia/issues/11092)).