gdi+ - Graphics.MeasureString 太宽或太窄

问题描述

我在 C# 中使用 System.Drawing 库来测量字符串的大小:

SizeF size = gfx.MeasureString("Hello",myFont);

然而,这会返回一个在文本周围有一点间距的大小。这是用红色边界框呈现的文本,表示返回的大小 MeasureString。框和文本的左上角完全相同。

Hello with a spacious bounding box

我在 Stack Overflow 上偶然发现 this question 建议使用 StringFormat.GenericTypographic 删除间距。所以我将代码更改为以下内容:

SizeF size = gfx.MeasureString("Hello",myFont,StringFormat.GenericTypographic);

产生以下结果(同样,框的左上角和文本相同):

Hello without spacing but the bounding box cuts into the text

几乎完美,但尺寸始终太窄并切入最后一个字母。这些结果可以用我尝试过的任何大小的任何字体、任何字符串和任何 width 参数重现。

我目前的解决方法是在绘制文本时将文本向左偏移 5 个像素。我错过了什么?

解决方法

事实证明,我还必须使用 StringFormat.GenericTypographic绘制字符串,而不仅仅是用它进行测量。新的 DrawString 调用如下所示:

gfx.DrawString("Hello",myFont,myBrush,topLeft,StringFormat.GenericTypographic);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...