Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize text size of a label when the text gets longer than the label size?

Tags:

I have a label that shows the file name .. I had to set AutoSize of the label to False for designing.
So when the file name text got longer than label size.. it got cut like in the picture.

enter image description here

label1.Size = new Size(200, 32); label1.AutoSize = false; 

How do I re-size the text automatically to fit the label size, when the text is longer than the label size?

like image 584
Murhaf Sousli Avatar asked Mar 02 '12 03:03

Murhaf Sousli


2 Answers

You can use my code snippet below. System needs some loops to calculate the label's font based on text size.

while(label1.Width < System.Windows.Forms.TextRenderer.MeasureText(label1.Text,       new Font(label1.Font.FontFamily, label1.Font.Size, label1.Font.Style)).Width) {     label1.Font = new Font(label1.Font.FontFamily, label1.Font.Size - 0.5f, label1.Font.Style); } 
like image 111
bnguyen82 Avatar answered Sep 21 '22 09:09

bnguyen82


Label scaling

private void scaleFont(Label lab) {     Image fakeImage = new Bitmap(1, 1); //As we cannot use CreateGraphics() in a class library, so the fake image is used to load the Graphics.     Graphics graphics = Graphics.FromImage(fakeImage);      SizeF extent = graphics.MeasureString(lab.Text, lab.Font);      float hRatio = lab.Height / extent.Height;     float wRatio = lab.Width / extent.Width;     float ratio = (hRatio < wRatio) ? hRatio : wRatio;      float newSize = lab.Font.Size * ratio;      lab.Font = new Font(lab.Font.FontFamily, newSize, lab.Font.Style); } 

TextRenderer Approach pointed out by @ToolmakerSteve in the comments

private void ScaleFont(Label lab) {     SizeF extent = TextRenderer.MeasureText(lab.Text, lab.Font);      float hRatio = lab.Height / extent.Height;     float wRatio = lab.Width / extent.Width;     float ratio = (hRatio < wRatio) ? hRatio : wRatio;      float newSize = lab.Font.Size * ratio;      lab.Font = new Font(lab.Font.FontFamily, newSize, lab.Font.Style); } 
like image 34
Andro72 Avatar answered Sep 18 '22 09:09

Andro72