如何确定哪些字体包含特定字符?

时间:2011-04-09 11:51:24

标签: c# .net fonts

给定一个特定的Unicode字符,让我们说吗,如何迭代系统中安装的所有字体并列出包含该字符字形的字体?

1 个答案:

答案 0 :(得分:13)

我已经在.NET 4.0上对此进行了测试,您需要添加对 PresentationCore 的引用以获取字体&工作的字体类型。另请查看Fonts.GetFontFamilies overloads

using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Windows.Media;

class Program
{
    public static void Main(String[] args)
    {
        PrintFamiliesSupprotingChar('a');
        Console.ReadLine();
        PrintFamiliesSupprotingChar('â');
        Console.ReadLine();
        PrintFamiliesSupprotingChar('嗎');
        Console.ReadLine();
    }

    private static void PrintFamiliesSupprotingChar(char characterToCheck)
    {
        int count = 0;
        ICollection<FontFamily> fontFamilies = Fonts.GetFontFamilies(@"C:\Windows\Fonts\");
        ushort glyphIndex;
        int unicodeValue = Convert.ToUInt16(characterToCheck);
        GlyphTypeface glyph;
        string familyName;

        foreach (FontFamily family in fontFamilies)
        {
            var typefaces = family.GetTypefaces();
            foreach (Typeface typeface in typefaces)
            {
                typeface.TryGetGlyphTypeface(out glyph);
                if (glyph != null && glyph.CharacterToGlyphMap.TryGetValue(unicodeValue, out glyphIndex))
                {
                    family.FamilyNames.TryGetValue(XmlLanguage.GetLanguage("en-us"), out familyName);
                    Console.WriteLine(familyName + " Supports ");
                    count++;
                    break;
                }
            }
        }
        Console.WriteLine();
        Console.WriteLine("Total {0} fonts support {1}", count, characterToCheck);
    }
}