Skip to main content
 首页 » 编程设计

c#之为什么 TextRenderer 在测量文本时添加边距

2024年02月13日10开发

由于在我的应用程序的某些地方缺少 Graphics 对象,我决定使用 TextRenderer 类。令人惊讶的是,它为测量文本增加了很多边距。例如:

private void button1_Click(object sender, EventArgs e) { 
 
    using (var g = this.CreateGraphics()) { 
 
        Font font = new Font("Calibri", 20.0f, GraphicsUnit.Pixel); 
        Size size = TextRenderer.MeasureText("Ala ma kota", font); 
 
        g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size)); 
        TextRenderer.DrawText(g, "Ala ma kota", font, new Point(10, 10), Color.Black); 
    } 
} 

给出以下结果:

为什么会这样?有没有办法强制它获得真实的文字大小? (当然,在它返回的同一个矩形中绘制它)

请您参考如下方法:

来自 MSDN :

For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces, use the versions of DrawText and MeasureText that take a Size and TextFormatFlags parameter, as shown in the example.

您还必须传递 Graphics 对象以获得正确的结果,因为:

This overload of MeasureText(String, Font, Size, TextFormatFlags) will ignore a TextFormatFlags value of NoPadding or LeftAndRightPadding. If you are specifying a padding value other than the default, you should use the overload of MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags) that takes a IDeviceContext object.

Size size = TextRenderer.MeasureText(g, 
                                     "Ala ma kota", 
                                     font, 
                                     new Size(int.MaxValue, int.MaxValue), 
                                     TextFormatFlags.NoPadding); 
 
TextRenderer.DrawText(g, "Ala ma kota", font, 
                      new Point(10, 10), 
                      Color.Black, 
                      TextFormatFlags.NoPadding); 
 
g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size)); 

另请查看直接使用 Graphics 方法:GDI+ MeasureString() is incorrectly trimming text