WinForms:度量文本而无填充 [英] WinForms: Measure Text With No Padding

查看:127
本文介绍了WinForms:度量文本而无填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinForms应用程序中,我试图测量要绘制的没有 的文本的大小.这是我得到的最接近的东西...

In a WinForms app, I am trying to measure the size of some text I want to draw with no padding. Here's the closest I've gotten...

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

...但是从结果中可以看到...

... but as you can see from the results ...

...仍然有大量的填充,特别是在顶部和底部.有什么方法可以测量绘制字符的实际边界(确实很糟糕,例如打印到图像然后寻找绘制的像素)?

... there is still a considerable amount of padding, particularly on the top and bottom. Is there any way to measure the actual bounds of the drawn characters (with something really awful like printing to an image and then looking for painted pixels)?

谢谢.

推荐答案

(我将这个答案标记为"the"答案,以便人们知道它已经被回答了,但是@TaW实际上提供了解决方案-参见上面的链接) )

(I've marked this answer as "the" answer just so people know it was answered, but @TaW actually provided the solution -- see his link above.)

@TaW-这就是窍门.我仍在努力使文字到达我想要的位置,但我实在是太过困难了.这是我最后得到的代码...

@TaW - That was the trick. I'm still struggling to get the text to go where I want it to, but I'm over the hump. Here's the code I ended out with...

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

...这是结果(请注意漂亮的紧边框)...

... and here is the result (notice the nice, tight bounding box) ...

这篇关于WinForms:度量文本而无填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆