Question

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?

Was it helpful?

Solution

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 ) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top