【问题标题】:How to extract set unicodes from an iconfont and display them in WPF如何从图标字体中提取设置的 unicode 并在 WPF 中显示它们
【发布时间】:2021-03-31 04:00:20
【问题描述】:

我想创建一个通用的图标选择器应用程序。您选择一个图标字体,应用程序会呈现所有可用的图标,您可以选择一个图标来复制它们的 unicode。

我发现了这篇文章Get supported characters of a font - in C#,我认为这正是我所需要的并实现了它。我已将找到的 unicode 放在 ObservableCollection 中,并将集合呈现为 ItemsControl。这确实可行,但显示的字形不是图标,而是通常的字母。

我的猜测是,我搞砸了从 ObservableCollection 中找到的字符到我的 unicode 字符的转换?

var families = Fonts.GetFontFamilies(openFileDialog.FileName);
foreach (FontFamily family in families)
{
    var typefaces = family.GetTypefaces();
    foreach (Typeface typeface in typefaces)
    {
        GlyphTypeface glyph;
        typeface.TryGetGlyphTypeface(out glyph);
        IDictionary<int, ushort> characterMap = glyph.CharacterToGlyphMap;

        foreach (KeyValuePair<int, ushort> kvp in characterMap)
        {
            //var iconChar = (char)kvp.Value;
            //Solution, changed to key instead of value
            var iconChar = (char)kvp.Key;

            // This is my OberservableCollection<char>
            this.FontCharacters.Add(iconChar);
        }
    }
}

我这样渲染:

<ScrollViewer DockPanel.Dock="Top">
    <ItemsControl ItemsSource="{Binding FontCharacters}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}" Style="{StaticResource IconButtonStyle}" FontFamily="pack://application:,,,/ProjectName;component/Fonts/#Font Awesome 5 Free Solid"></Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>

#Update:我解决了这个问题,我只需要使用它们 kvp.Key 而不是值,现在就会显示正确的图标。

【问题讨论】:

  • 如果您解决了自己的问题,您应该将解决方案放在下面的“您的答案”框中。大约一天后,您可以接受自己的答案,您的问题将在 UI 中标记为已回答。
  • @DourHighArch 是的,这是不可能的,因此更新了,但感谢您的提醒,我现在就这样做!

标签: .net wpf xaml


【解决方案1】:

上述代码的问题是,使用 kvp.Value 代替 kvp.Key。

工作代码:

var families = Fonts.GetFontFamilies(openFileDialog.FileName);
foreach (FontFamily family in families)
{
    var typefaces = family.GetTypefaces();
    foreach (Typeface typeface in typefaces)
    {
        GlyphTypeface glyph;
        typeface.TryGetGlyphTypeface(out glyph);
        IDictionary<int, ushort> characterMap = glyph.CharacterToGlyphMap;

        foreach (KeyValuePair<int, ushort> kvp in characterMap)
        {
            //Solution, changed to key instead of value
            var iconChar = (char)kvp.Key;

            // This is my OberservableCollection<char>
            this.FontCharacters.Add(iconChar);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2019-04-22
    • 2017-04-24
    相关资源
    最近更新 更多