【坑】GDI+中的MeasureString

一整个字符拿去measure确实是不怎么容易遇上问题。但是你要一个一个来的话,就会有问题。原因是msdn里有这么一句话:

The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs.

INCLUDES A SMALL AMOUNT OF EXTRA SPACE BEFORE AND AFTER THE STRING

所以获取到的会偏大。

方法它也说得挺清楚

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.

没注意的话很容易掉坑

后续补充:MeasureString的时候要加StringFormat.GenericTypographic,那么在DrawString的时候也要一起加这个参数。不然它计算的时候和绘制的时候宽度又不一样了

发表评论