Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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.

like image 431
Martin Marconcini Avatar asked Dec 23 '08 14:12

Martin Marconcini


People also ask

Which property is required to change the size of a label?

The AutoSize property helps you size the controls to fit larger or smaller captions, which is particularly useful if the caption will change at run time.


1 Answers

How about Graphics.MeasureString, with the overload that accepts a string, the font, and the max width? This returns a SizeF, so you can round round-off the Height.

        using(Graphics g = CreateGraphics()) {             SizeF size = g.MeasureString(text, lbl.Font, 495);             lbl.Height = (int) Math.Ceiling(size.Height);             lbl.Text = text;         } 
like image 162
Marc Gravell Avatar answered Sep 24 '22 08:09

Marc Gravell