Search code examples
c#system.drawingmeasurestringsystem.drawing.graphics

System.Drawing.Graphics trim end of string?


While working on a text render algorithm, I stumbled across a strange behavior of the Graphics.MeasureString() method.

It seems like it internally trims the end of a string.

g.MeasureString("d", font).Width //is 13.289278
g.MeasureString("d ", font).Width //is 13.2892771
g.MeasureString(" d", font).Width //is 17.4858913
//font.Size = 11; font.FontFamily = "Arial";

Can someone explain this behaviour?


Solution

  • As from MSDN description of MeasureTrailingSpaces format flag:

    By default the boundary rectangle returned by the MeasureString method excludes the space at the end of each line. Set this flag to include that space in measurement.

    So if you will provide this flag - results will be the same

    var fmt = new StringFormat(StringFormatFlags.MeasureTrailingSpaces);
    var x2 = g.MeasureString("d ", font, 0, fmt).Width;
    var x3 = g.MeasureString(" d", font, 0, fmt).Width;