2011-02-17 44 views
3

我正在使用(C#,.NET 2.0)中的翻譯軟件添加工具,它在模擬設備顯示中顯示翻譯後的文本。 我必須檢查是否所有翻譯的文本都可以使用指定的字體顯示(Windows TTF)。 但我沒有找到任何方法來檢查字體的不支持的字形。 有沒有人有想法?C#:檢查字體中不支持的字符/字形

謝謝

回答

5

您是否僅限於.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()); 
} 
+0

感謝您的回答。 – Marco 2011-02-23 06:20:11