gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:44 27 4
gpt4 key购买 nike

由于在我的应用程序的某些地方缺少 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);
}
}

给出以下结果:

Text with margins

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

最佳答案

来自 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

关于c# - 为什么 TextRenderer 在测量文本时添加边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22955612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com