Setting FontFamily at runtime (custom font)? #17199
-
First of all, I want to say thank you to Avalonia for producing the following for packaging custom fonts: https://docs.avaloniaui.net/docs/guides/styles-and-resources/how-to-use-fonts It always been a confusing topic and error prone, so its incredibly helpful, however, I still I have no real idea how to set TextBlock.Font family at runtime. In the past, I have spent days pouring over this issue, and sometimes it works, and then it doesn't. I primarily want to do this at runtime, and all the examples seem to be XAML. Please have patience with me on this. So lets suppose I wish to use a custom font I've packaged as a resource, so I include the following the csproj:
Then in the App.axaml:
So what should FontFamily be at runtime? TextBlock.FontFamily = "NunitoFont" ? Or something else? PS. How is FontFamily handled if I do something like: TextBlock.FontFamily = "serif" This doesn't seem to do anything, so I'm guessing if falls to "Inter". What happens if I set just: TextBlock.FontFamily = "Inter" ? Does it find "Inter", or does it not find it, but then falls back to Inter? This is relevant where the Family needs to be set from a drop down box at the UI. Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
TextBlock.FontFamily = new FontFamily(@"avares://AvaloniaApplication/Assets/Fonts#Nunito"); // For a resource-based font
TextBlock.FontFamily = new FontFamily("Times New Roman"); // For a system font I tend to store these in a public static class AppResources
{
public static FontFamily Nunito { get; } = new FontFamily(@"avares://AvaloniaApplication/Assets/Fonts#Nunito");
} However, I'm not able to create+add an Avalonia/src/Avalonia.Base/Media/FontManager.cs Lines 130 to 138 in aabd038 So I can't get something like this to work: var fc = new EmbeddedFontCollection(new Uri("fonts:App", UriKind.Absolute), new Uri(@"avares://AvaloniaApplication/Assets", UriKind.Absolute));
FontManager.Current.AddFontCollection(fc);
text.FontFamily = new FontFamily("Nunito"); When I try using var ff = new FontFamily(new Uri("fonts:App"), "Nunito");
var tf = new Typeface(ff);
FontManager.Current.TryGetGlyphTypeface(tf, out var gtf); That's about as far as I can troubleshoot for now. (Actual testing was done with Anton SC as Nunito looks too similar to Inter) |
Beta Was this translation helpful? Give feedback.
Ah, good to know. Thanks!
For anybody following along, this is possible today (fixing my example above):
It leaks a bit of font storage knowledge vs simply "Nunito", so I do wish any added
FontCollection
s would be searched before the default font is used, but I might be bikeshedding.I still prefer the
static class
approach if your entire set of custom fonts is known at compile-time and come from resources.