如何获得字体大小(以像素为单位)?

时间:2012-01-17 14:28:44

标签: .net graphics gdi+

我最初的直觉是通过Graphics实例获取系统的当前DpiY设置,但我无法弄清楚如何获得它。

通过Reflector进行拼写我看到Microsoft使用不安全的代码管理它:

IntPtr dC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
    using (Graphics graphics = Graphics.FromHdcInternal(dC))
    {
        float num = graphics.DpiY;
    }
}

当我没有图形时,构建图形的管理等效方法是什么?

我试过了:

using (Graphics g = Graphics.FromHdc(IntPtr.Zero))
{
    return font.GetHeight(g.DpiY);
}

但是抛出值不能为空异常。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用不使用TextRendering对象的Graphics方法:

int textHeight = TextRenderer.MeasureText("Text", this.Font).Height;

或者如果需要,您可以自己快速Graphic

float textHeight;
using (Bitmap b = new Bitmap(1,1))
using (Graphics g = Graphics.FromImage(b)) {
  textHeight = this.Font.GetHeight(g.DpiY);
}
相关问题