Avalonia.HtmlRenderer icon indicating copy to clipboard operation
Avalonia.HtmlRenderer copied to clipboard

How to use a font that is an Avalonia resource?

Open bmscodespace opened this issue 1 year ago • 5 comments
trafficstars

Hi,

thank you all for the HtmlRenderer project. Is there a way to use as "font-family" a font that is registered in the Avalonia resources? F.e. I have added "Work Sans" to my resources and now want to do something like

<Style Selector="html|HtmlLabel">
            <Setter Property="BaseStylesheet" Value="* { font-family: 'Work Sans'; src: url(???)}" />
</Style>

where I at the moment don't know what to write in place of "???". Thank you very much for any help ;)

bmscodespace avatar Oct 07 '24 10:10 bmscodespace

In HtmlContainer class, there is AddFontFamilyMapping method. You can map your CSS font name to Avalonia font with this method.

maxkatz6 avatar Oct 07 '24 23:10 maxkatz6

"In HtmlContainer class, there is AddFontFamilyMapping method. You can map your CSS font name to Avalonia font with this method."

Oh, thank you, I will try that out ;)

Hm, it seems that the nuget package (i installed it using dotnet add package Avalonia.HtmlRenderer --version 11.0.0 ) seems to be not as up to date as the code in the repository. There seems to be no function AddFontFamilyMapping in the HtmlContainer class of the package. Is it possible to solve my problem above using the package?

bmscodespace avatar Oct 08 '24 08:10 bmscodespace

ps .. using the package, I have tried the following: I added the font using HtmlRender.AddFontFamily(new FontFamily(new Uri("avares://..../Assets/Fonts#Work Sans"), "Work Sans")); before the xaml is loaded and then tried to use the font as follows:

<html:HtmlLabel
      Name = "SomeTestLabel"
      Margin="8,8,8,8"
      Text="Some Text"
      BaseStylesheet="* { font: 15.35px 'Work Sans'; color: #111; }"
 />

But somehow sadly it did not work, hm ....

bmscodespace avatar Oct 08 '24 10:10 bmscodespace

Hi again. Will the nuget package be updated to the current code?

bmscodespace avatar Oct 24 '24 09:10 bmscodespace

I was able to use it like this:

if (Avalonia.Application.Current.TryGetResource("FigtreeFont", appl.ActualThemeVariant, out var fontRes) && fontRes != null)
{
    htmlPanel.Container.AddFontFamily((FontFamily)fontRes);
    htmlPanel.Container.AddFontFamilyMapping("monospace", "Figtree");
}

But only when using "monospace". Other font families or trying to use Figtree directly in the css did not work. Not sure why.

MuhKuh7 avatar Apr 27 '25 14:04 MuhKuh7