Reputation:
If I calculate size in terms of width for text using below it give me says 500
intWidth = (int)objGraphics.MeasureString(String.concat(sImageText1, sImageText2), objFont).Width;
but if i do like this
intWidth = (int)objGraphics.MeasureString(sImageText1, objFont).Width + (int)objGraphics.MeasureString(sImageText2, objFont).Width;
I search lot and have done lots of different scenarios but still getting difference if we measure string width using "MeasureString" with full text or part by part.
Why is this?
Upvotes: 3
Views: 306
Reputation: 391276
The documentation has the answer:
The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString. To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
The emphasized parts are what is relevant here.
To fix your code, add the necessary parameters:
intWidth = (int)objGraphics.MeasureString(sImageText1, objFont, 1024, Stringformat.GenericTypographic).Width
+ (int)objGraphics.MeasureString(sImageText2, objFont, 1024, StringFormat.GenericTypographic).Width;
Upvotes: 6