WinForms:测量没有填充的文本

WinForms: Measure Text With No Padding

在 WinForms 应用程序中,我正在尝试测量要绘制的一些文本的大小没有填充。这是我得到的最接近的...

    protected override void OnPaint(PaintEventArgs e) {
        DrawIt(e.Graphics);
    }

    private void DrawIt(Graphics graphics) {
        var text = "123";
        var font = new Font("Arial", 32);
        var proposedSize = new Size(int.MaxValue, int.MaxValue);
        var measuredSize = TextRenderer.MeasureText(graphics, text, font, proposedSize, TextFormatFlags.NoPadding);
        var rect = new Rectangle(100, 100, measuredSize.Width, measuredSize.Height);
        graphics.DrawRectangle(Pens.Blue, rect);
        TextRenderer.DrawText(graphics, text, font, rect, Color.Black, TextFormatFlags.NoPadding);
    }

...但是从结果可以看出...

...仍有大量填充,尤其是在顶部和底部。有什么方法可以测量绘制字符的实际边界(有些东西真的很糟糕,比如打印到图像然后寻找绘制的像素)?

提前致谢。

你试过了吗

Graphics.MeasureString("myString", myFont, int.MaxValue, StringFormat.GenericTypographic)

(我已将此答案标记为 "the" 答案只是为了让人们知道它已被回答,但 @TaW 实际上提供了解决方案——请参阅上面他的 link。)

@TaW - 这就是诀窍。我仍在努力让文本到达我想要的位置,但我已经克服了困难。这是我最终得到的代码...

    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        DrawIt(e.Graphics);
    }

    private void DrawIt(Graphics graphics) {
        var text = "123";
        var font = new Font("Arial", 40);
        // Build a path containing the text in the desired font, and get its bounds.
        GraphicsPath path = new GraphicsPath();
        path.AddString(text, font.FontFamily, (int)font.Style, font.SizeInPoints, new Point(0, 0), StringFormat.GenericDefault);
        var bounds = path.GetBounds();
        // Move it where I want it.
        var xlate = new Matrix();
        xlate.Translate(100, 100);
        path.Transform(xlate);
        // Draw the path (and a bounding rectangle).
        graphics.DrawPath(Pens.Black, path);
        bounds = path.GetBounds();
        graphics.DrawRectangle(Pens.Blue, bounds.Left, bounds.Top, bounds.Width, bounds.Height);
    }

...这是结果(注意漂亮、紧凑的边界框)...