How to measure the exact width of String in pixels in Winforms

2.6k Views Asked by At

I need to measure the exact pixel size of a string in label control in Winforms. I tried with TextRenderer.MeasureText(Text, Font) and graphics.MeasureString(Text, Font) but didn't get exact pixel width.

When checked the exact pixel width it is 90 but TextRenderer and Graphics are giving different values. Can anyone help me on this.

enter image description here

1

There are 1 best solutions below

1
On

Please note what is written in the TextRendered.MeasureText documentation (emphasis mine):

Return Value
Type: System.Drawing.Size
The Size, in pixels, of text drawn on a single line with the specified font. You can manipulate how the text is drawn by using one of the DrawText overloads that takes a TextFormatFlags parameter. For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces you should use the versions of DrawText and MeasureText that take a Size and TextFormatFlags parameter. For an example, see MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags).

Also, please note that the Graphics.MeasureString documentation (again, emphasis mine):

Remarks
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.