Winforms MeasureText不';t对应于没有TextFormatFlags的DrawText。单线,解决方法?
我想测量矩形内的文本,但它仅在格式标志包括TextFormatFlags.SingleLine时才能正常工作 在窗体上放置一个面板,并添加此Paint事件处理程序Winforms MeasureText不';t对应于没有TextFormatFlags的DrawText。单线,解决方法?,winforms,gdi+,Winforms,Gdi+,我想测量矩形内的文本,但它仅在格式标志包括TextFormatFlags.SingleLine时才能正常工作 在窗体上放置一个面板,并添加此Paint事件处理程序 private void panel1_Paint(object sender, PaintEventArgs e) { TextFormatFlags flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextF
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);
}
你会看到这个
但是如果你把国旗上的单线去掉
TextFormatFlags flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Left;
然后你得到这个
我不认为这种行为是故意的,但不管怎样,我能很容易地克服它吗
谢谢对不起,写出来给了我需要的解决方案
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中的一个错误,那么解决方法就是使用此方法…很好奇否决票是为了什么,是的,我确实解决了我自己的问题,但它仍然是其他人可能遇到的一个有效问题。两天之内我不能接受自己的回答。。。