7

Please see my code:

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1));

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular);

const string text1 = "check_space";
SizeF bounds1 = grfx.MeasureString(text1, f);

const string text2 = "check_space ";
SizeF bounds2 = grfx.MeasureString(text2, f);

Assert.IsTrue(bounds1.Width < bounds2.Width); // I have Fail here!

I wonder why my test is failed. Why text with space in tail is NOT greater by width than text without space?

UPDATE: I can understand these both strings are not equal. But as I mentally understand the string with space should be greater by width than the string without space. Don't?

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Michael Z
  • 3,883
  • 10
  • 43
  • 57

1 Answers1

15

you have to tell it to measure trailing spaces, which it does not by default.

Graphics grfx = Graphics.FromImage(new Bitmap(1, 1));

System.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular);

string text1 = "check_space";
SizeF bounds1 = grfx.MeasureString(text1, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ));

string text2 = "check_space ";
SizeF bounds2 = grfx.MeasureString(text2, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );
Timmerz
  • 6,090
  • 5
  • 36
  • 49