Alex Rivera | Logout

Determine Label Size based upon amount of text and font size in Winforms/C#

Asked 2008-12-23T14:12:22.877
48

I'd like to know if there's a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (about 60 chars wide before it must wrap), about 495 pixels. The font is also a fixed size (12points afaik), but the text is not.

What I want to do is increase the Label Height when there's a "NewLine" or the text must wrap; the idea is that the text is fully visible in the label. The AutoSize doesn't work because it will grow in width, not in height.

Of course I could count the number of NewLines and add: Newlines * LineHeight, and then -given that I manage to put 60 chars per line, just divide the number of chars and add as many LineHeight pixels as needed.

I was wondering if there was a more professional way to do it. Is my approach too "lame" ?

Thanks in advance.

Edit
Report

1 Answer

1

I posted a user control which solves this problem in the accepted answer here: Autoscale Font in a TextBox Control so that its as big as possible and still fits in text area bounds

The control extends RichTextBox. It has a method: ScaleFontToFit that will automatically resize the font to make all the text fit.

Neat thing is it respects the multiline property. If it's true it allows words to wrap, Otherwise it doesn't.

answered 2012-05-30T13:27:23.547

Your Answer