質問

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.

http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

他のヒント

ToSize() truncates values of the SizeF to the next lower integer values.

So, to avoid losses you can do something like that:

l.Size = (CreateGraphics().MeasureString(_name, l.Font) + new SizeF(1, 0)).ToSize();

Is it something as simple as getting the size wrong when you declare your font compared to the UI font size?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top