MeasureString()填充左侧和右侧的文本
时间:2020-03-06 14:34:36 来源:igfitidea点击:
我在C ++中使用GDI +。 (此问题可能在Ctoo中存在)。
我注意到,每当我调用Graphics :: MeasureString()或者Graphics :: DrawString()时,该字符串就会在左右两侧填充空白。
例如,如果我使用的是Courier字体(不是斜体!),并且我测量" P",我得到90,但是" PP"给我150。我希望等宽字体的宽度恰好是" PP"的两倍。 。
我的问题是:这是预期的还是已记录的行为,如何禁用此行为?
RectF Rect(0,0,32767,32767); RectF Bounds1, Bounds2; graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1); graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2); margin = Bounds1.Width * 2 - Bounds2.Width;
解决方案
这是设计使然,该方法不使用实际的字形来测量宽度,因此在悬垂的情况下会增加一些填充。
如果我们需要更高的准确性,MSDN建议使用其他方法:
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
根据这篇kb文章,听起来好像也可能与提示有关,为什么使用GDIPlus与GDI绘制文本时文本看起来会有所不同
确实是设计使然,但是接受的答案上的链接实际上并不完美。问题是,当我们真正要使用的是像素(整数)时,在所有这些方法中都使用浮点数。
TextRenderer类就是为此目的而设计的,并且可以使用实际大小。请参阅msdn的此链接,以获取使用此链接的演练。
TextRenderer非常适合获取字体大小。但是在绘制循环中,与graphics.DrawString()相比,使用TextRenderer.DrawText的速度非常慢。
由于字符串的宽度是问题所在,因此最好结合使用TextRenderer.MeasureText和graphics.DrawString.。