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:
So here is the function:
Note: You have to define the Maximumsize and default font in your label properties.
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:
- Graphics variable
- Text string - which you want to fit
- Maximum size in points(Property of Label)- in which text need to fit
- 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); }