Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

.net - C#: Check for unsupported characters/glyphs in a font

I am working on a translation software add in (C#, .NET 2.0) which displays translated texts in a emulated device display. I have to check if all translated texts could be displayed with specified fonts (Windows TTF). But I didn't found any way to check a font for unsupported glyphs. Does anyone have an idea?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are you limited to .NET 2.0? In .NET 3.0 or higher, there's the GlyphTypeface class, which can load a font file and exposes the CharacterToGlyphMap property, which I believe can do what you want.

In .NET 2.0, I think you'll have to rely on PInvoke. Try something like:

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()); 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...