C# · 12月 31, 2021

c# – 确定指定字体中的精确字形高度

我搜索了很多,尝试了很多,但我找不到正确的解决方案.

我想知道有什么方法可以确定指定字体中的精确字形高度?

我的意思是这里,当我想确定DOT字形的高度,我应该收到小高度,但不是高度与paddings或字体大小.

我找到了确定精确字形宽度here(我已经使用第二种方法)的解决方案,但它不适用于高度.

更新:我需要.NET 1.1的解决方案

解决方法 获取角色指标并不难. GDI包含一个函数 GetGlyphOutline,您可以使用GGO_METRICS常量调用该函数,以获取在呈现时包含字形所需的最小包围矩形的高度和宽度.即,字体Arial中的点的10点字形将给出一个1×1像素的矩形,对于字母I 95x.14,如果字体的大小为100点.

这些是P / Invoke电话的声明:

// the declarationspublic struct FIXED{ public short fract; public short value;}public struct MAT2{ [MarshalAs(UnmanagedType.Struct)] public FIXED eM11; [MarshalAs(UnmanagedType.Struct)] public FIXED eM12; [MarshalAs(UnmanagedType.Struct)] public FIXED eM21; [MarshalAs(UnmanagedType.Struct)] public FIXED eM22;}[StructLayout(LayoutKind.Sequential)]public struct POINT{ public int x; public int y;}[StructLayout(LayoutKind.Sequential)]public struct POINTFX{ [MarshalAs(UnmanagedType.Struct)] public FIXED x; [MarshalAs(UnmanagedType.Struct)] public FIXED y;}[StructLayout(LayoutKind.Sequential)]public struct GLYPHMETRICS{ public int gmBlack@R_868_2419@X; public int gmBlack@R_868_2419@Y; [MarshalAs(UnmanagedType.Struct)] public POINT gmptGlyphOrigin; [MarshalAs(UnmanagedType.Struct)] public POINTFX gmptfxGlyphOrigin; public short gmCellIncX; public short gmCellIncY;}private const int GGO_METRICS = 0;private const uint GDI_ERROR = 0xFFFFFFFF;[DllImport(“gdi32.dll”)]static extern uint GetGlyphOutline(IntPtr hdc,uint uChar,uint uFormat,out GLYPHMETRICS lpgm,uint cbBuffer,IntPtr lpvBuffer,ref MAT2 lpmat2);[DllImport(“gdi32.dll”,ExactSpelling = true,PreserveSig = true,SetLastError = true)]static extern IntPtr SelectObject(IntPtr hdc,IntPtr hgdiobj);

实际的代码,相当琐碎,如果你不考虑P / Invoke的冗余.我测试了代码,它工作(您可以调整以获得宽度从GLYPHMETRICS).

注意:这是特设代码,在现实世界中,您应该使用ReleaseHandle和DeleteObject清理HDC和对象.感谢user2173353的评论指出了这一点.

// if you want exact metrics,use a high font size and divide the result// otherwise,the resulting rectangle is rounded to nearest intprivate int GetGlyphHeight(char letter,string fontName,float fontPointSize){ // init the font. Probably better to do this outside this function for performance Font font = new Font(new FontFamily(fontName),fontPointSize); GLYPHMETRICS metrics; // identity matrix,required MAT2 matrix = new MAT2 { eM11 = {value = 1},eM12 = {value = 0},eM21 = {value = 0},eM22 = {value = 1} }; // HDC needed,we use a bitmap using(Bitmap b = new Bitmap(1,1)) using (Graphics g = Graphics.FromImage(b)) { IntPtr hdc = g.GetHdc(); IntPtr prev = SelectObject(hdc,font.ToHfont()); uint retVal = GetGlyphOutline( /* handle to DC */ hdc,/* the char/glyph */ letter,/* format param */ GGO_METRICS,/* glyph-metrics */ out metrics,/* buffer,ignore */ 0,ignore */ IntPtr.Zero,/* trans-matrix */ ref matrix); if(retVal == GDI_ERROR) { // something went wrong. Raise your own error here,// or just silently ignore return 0; } // return the height of the smallest rectangle containing the glyph return metrics.gmBlack@R_868_2419@Y; } }