Change label text font size dynamically based on string length

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vijeta
    New Member
    • Jul 2011
    • 1

    Change label text font size dynamically based on string length

    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:
    Code:
    private Font GetCorrectFont(Graphics graphic, String   text, Size maxStringSize, Font labelFont)
    {
      //based on the Label string,we need to vary font size 
      //current width the text string
      SizeF sizeStr = graphic.MeasureString(text, labelFont);
      Font fontStr = new Font(labelFont.Name,labelFont.Size);
      while (sizeStr.Width > maxStringSize.Width)
      {
        //adjust the font size based on width ratio
        float wRatio = (maxStringSize.Width) / sizeStr.Width;
        //reduce the font size
        float newSize = (int)(fontStr.Size * wRatio); 
     //this creates a new font with given fontfamily name
        fontStr = new Font(labelFont.Name, newSize); 
        sizeStr = graphic.MeasureString(text, fontStr);
       }
       return fontStr;
    }
    
    //Calling convention
    //I have a label in my GUI, I need to call this function on "Paint" event
    
    private void lblIncrease_Paint(object sender, PaintEventArgs e)
    {
     lblIncrease.Font =  GetCorrectFont(e.Graphics, lblIncrease.Text, lblIncrease.MaximumSize, lblIncrease.Font);
    }
    Note: You have to define the Maximumsize and default font in your label properties.
    Last edited by Niheel; Jul 7 '11, 03:11 AM. Reason: Edited to make it more readable. Thanks for writing an article :)
Working...