如果没有TextFormatFlags.SingleLine,MeasureText与DrawText不对应,解决方法?

时间:2013-08-07 18:38:22

标签: winforms gdi+

我想测量矩形内的文本,但只有当格式标志包含TextFormatFlags.SingleLine时它才能正常工作。

EG。将面板放在窗体上并添加此Paint事件处理程序

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        TextFormatFlags flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.Left;
        Panel panel = (sender as Panel);

        //Draw the text
        TextRenderer.DrawText(e.Graphics, "hello", SystemFonts.DefaultFont, new Rectangle(0, 0, panel.Bounds.Width, panel.Bounds.Height), Color.Red, flags);

        //Draw a border around the panel
        e.Graphics.DrawRectangle(System.Drawing.Pens.Black, 0, 0, panel.Width - 1, panel.Height - 1);

        //Measure the text and draw a rect around it
        Size s = TextRenderer.MeasureText(e.Graphics, "hello", SystemFonts.DefaultFont, new Size(panel.Bounds.Width, panel.Bounds.Height), flags);
        e.Graphics.DrawRectangle(Pens.Blue, 0, 0, s.Width, s.Height);


    }

你会看到这个

Working screenshot

但如果您在旗帜中取出SingleLine;

        TextFormatFlags flags =  TextFormatFlags.VerticalCenter | TextFormatFlags.Left;

然后你得到了这个

enter image description here

我不认为这种行为是设计的,但不管怎样,我可以轻松解决这个问题吗?

谢谢

1 个答案:

答案 0 :(得分:0)

抱歉,写出来给了我所需的解决方案。

    private Size FixMeasureText(Graphics graphics, string p, Font font, Size size, TextFormatFlags flags)
    {
        Size s = TextRenderer.MeasureText(graphics, p, font, size, flags);
        if ((flags & TextFormatFlags.SingleLine )== 0)//need to fix
        {
            s.Height = ((size.Height - s.Height) / 2 )+ s.Height;
        }
        return s;

    }

因此,如果它确实是TextRenderer.MeasureText中的错误,那么解决方案就是使用此方法代替......