4

我正在开发一个翻译软件插件(C#,.NET 2.0),它在模拟设备显示器中显示翻译的文本。我必须检查是否所有翻译的文本都可以使用指定的字体显示(Windows TTF)。但我没有找到任何方法来检查不受支持的字形的字体。有人有想法吗?

谢谢

4

1 回答 1

8

您是否仅限于 .NET 2.0?在 .NET 3.0 或更高版本中,有一个GlyphTypeface类,它可以加载字体文件并公开CharacterToGlyphMap属性,我相信它可以做你想做的事。

在 .NET 2.0 中,我认为您将不得不依赖 PInvoke。尝试类似:

using System.Drawing;
using System.Runtime.InteropServices;

[DllImport("gdi32.dll", EntryPoint = "GetGlyphIndicesW")]
private static extern uint GetGlyphIndices([In] IntPtr hdc, [In] [MarshalAs(UnmanagedType.LPTStr)] string lpsz, int c, [Out] ushort[] pgi, uint fl);

[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);

private const uint GGI_MARK_NONEXISTING_GLYPHS = 0x01;

// Create a dummy Graphics object to establish a device context
private Graphics _graphics = Graphics.FromImage(new Bitmap(1, 1));

public bool DoesGlyphExist(char c, Font font)
{
  // Get a device context from the dummy Graphics 
  IntPtr hdc = _graphics.GetHdc();
  ushort[] glyphIndices;

  try {
    IntPtr hfont = font.ToHfont();

    // Load the font into the device context
    SelectObject(hdc, hfont);

    string testString = new string(c, 1);
    glyphIndices = new ushort[testString.Length];

    GetGlyphIndices(hdc, testString, testString.Length, glyphIndices, GGI_MARK_NONEXISTING_GLYPHS);

  } finally {

    // Clean up our mess
    _graphics.ReleaseHdc(hdc);
  }

  // 0xffff is the value returned for a missing glyph
  return (glyphIndices[0] != 0xffff);
}

private void Test()
{
  Font f = new Font("Courier New", 10);

  // Glyph for A is found -- returns true
  System.Diagnostics.Debug.WriteLine(DoesGlyphExist('A', f).ToString()); 

  // Glyph for ಠ is not found -- returns false
  System.Diagnostics.Debug.WriteLine(DoesGlyphExist((char) 0xca0, f).ToString()); 
}
于 2011-02-22T16:56:35.890 回答