By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,034 Members | 1,361 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Change label text font size dynamically based on string length

P: 1
Well, I came across a problem in which based on system selected language, my label text will change. This is called Localization in C#/.Net (Localization is a technique to implement local and culture-oriented applications). So if a label string is "Increase" the same string in Bugarian language will be "Увеличаване на скоростта".

So what we see from above example, that the text size changes with change in language.

If I want to limit the maximum size in which text should fit, then I need to change the font for that text.

To do so, we need following parameters:
  1. Graphics variable
  2. Text string - which you want to fit
  3. Maximum size in points(Property of Label)- in which text need to fit
  4. Default Font

So here is the function:
Expand|Select|Wrap|Line Numbers
  1. private Font GetCorrectFont(Graphics graphic, String   text, Size maxStringSize, Font labelFont)
  2. {
  3.   //based on the Label string,we need to vary font size 
  4.   //current width the text string
  5.   SizeF sizeStr = graphic.MeasureString(text, labelFont);
  6.   Font fontStr = new Font(labelFont.Name,labelFont.Size);
  7.   while (sizeStr.Width > maxStringSize.Width)
  8.   {
  9.     //adjust the font size based on width ratio
  10.     float wRatio = (maxStringSize.Width) / sizeStr.Width;
  11.     //reduce the font size
  12.     float newSize = (int)(fontStr.Size * wRatio); 
  13.  //this creates a new font with given fontfamily name
  14.     fontStr = new Font(labelFont.Name, newSize); 
  15.     sizeStr = graphic.MeasureString(text, fontStr);
  16.    }
  17.    return fontStr;
  18. }
  20. //Calling convention
  21. //I have a label in my GUI, I need to call this function on "Paint" event
  23. private void lblIncrease_Paint(object sender, PaintEventArgs e)
  24. {
  25.  lblIncrease.Font =  GetCorrectFont(e.Graphics, lblIncrease.Text, lblIncrease.MaximumSize, lblIncrease.Font);
  26. }
Note: You have to define the Maximumsize and default font in your label properties.
Jul 6 '11 #1
Share this Article
Share on Google+