I have the following code to create a Label
on a PictureBox
:
Label l = new Label();
l.Text = _name;
l.Size = CreateGraphics().MeasureString(_name, l.Font).ToSize();
l.BackColor = Color.White;
but the label is always dropping the last character. If I add a character to the call:
l.Size = CreateGraphics().MeasureString(_name+".", l.Font).ToSize();
it works fine, but that doesn't feel right.
There seems to be some white space just before the text in the label, but Padding
is set to 0. How can I fix this the correct way?
Can't you use the AutoSize
property?
MeasureString
is notoriously inaccurate, though normally it returns a size bigger than you'd expect:
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.