Skip to content

SP5 Label: changing font name or style should blow the cache #3236

@kl7107

Description

@kl7107

Issue: Label.cs strings are not shown using the requested FontName.

When using WPF, Title / XLabel / YLabel are always shown using the font "Segoe UI", even when a different font is set.

Expected result:
expected

Actual result:
actual

ScottPlot Version: v5.0.18

Code Sample:

// XAML: <sp:WpfPlot Name="WpfPlot1" />
WpfPlot1.Plot.Title("测试");
WpfPlot1.Plot.XLabel("测试");
WpfPlot1.Plot.YLabel("已占用");
WpfPlot1.Plot.Style.SetBestFonts();
WpfPlot1.Refresh();
WpfPlot1.Plot.SavePng("bug.png", 300, 300);

Possible root cause:

The root cause seems to be that the Skia typeface is cached in Label.cs. (Property CachedTypeface)

Once it is cached, it is never updated, even when the Label.cs:FontName property is changed.

It still works in Avalonia as long as all FontNames are set before the first Render() call is made by the user code.

But after that, the FontName property is ignored.

It does not work in WPF since the WPF control seems to make an automatic Render() call before the start of the user code. This locks in the default FontName.

WPF render() call:

Plot.Render(e.Surface.Canvas, rect);

When changing the Label.cs properties as below, the fonts render as expected:

private SKTypeface? _cachedTypeface = null;
public SKTypeface? CachedTypeface
{
    get
    {
        return _cachedTypeface;
    }
    set
    {
        Debug.WriteLine($"CachedTypeface set: Label text = '{Text}', typeface = '{value?.FamilyName}'");
        _cachedTypeface = value;
    }
}

private SKTypeface Typeface
{
    get
    {
        if (_cachedTypeface == null)
        {
            Debug.WriteLine($"Label.cs:Typeface.get(): _cachedTypeface == null. Text = '{Text}'");
        }
        return CachedTypeface ??= FontStyle.CreateTypeface(FontName, Bold, Italic);
    }
}

private string fontName = Fonts.Default;
public string FontName
{
    get => fontName; 
    set
    {
        fontName = value;
        if (CachedTypeface != null)
        {
            CachedTypeface.Dispose();
            CachedTypeface = FontStyle.CreateTypeface(FontName, Bold, Italic);
        }
    }
}

NOTE: This is just a quick test, and not a well designed implementation. At a minimum, the Bold and Italic properties should probably also trigger updates?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions