我想测量一个矩形内的文本,但它只有在格式标志包括 TextFormatFlags.SingleLine 时才能正常工作。
例如。在表单上放置一个面板并添加此 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);
}
你会看到这个
但是如果您在标志中取出 SingleLine;
TextFormatFlags flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Left;
然后你得到这个
我不认为这种行为是设计使然,但无论哪种方式,我可以轻松解决它吗?
谢谢