Measuring a row using Graphics.MeasureString

Check out 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 failed. Why is the text with the tail NOT longer in width than the text without space?

UPDATE: I understand that both lines are not equal. But since I mentally understand that the line with should be wider than the line without . Not?

+6
source share
1 answer

you must tell him to measure trailing spaces that are not fulfilled 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 ) ); 
+12
source

Source: https://habr.com/ru/post/911788/


All Articles