Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String measurement with Graphics.MeasureString

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?

like image 570
Michael Z Avatar asked Mar 27 '12 19:03

Michael Z


1 Answers

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 ) );
like image 76
Timmerz Avatar answered Nov 06 '22 05:11

Timmerz