Hi, This is my first article in the forum. If there is no clarity in the article, let me know. Recently i have a requirement for resizing the text to a fixed cell width in a web application. Clearly, When a user enters his Name in a text box, we need to display that name in header as large as possible depend on the length of his name.
I achieved this by making use of Graphics class in C#.net. For this i used a single function getFontSize.
Name spaces required System.Drawing,System.Drawing.Imaging,System.Drawing.Drawing2D
public string getfontsize(string userName) { string fntval = ""; for (int i = 48; i >= 10; i--) { Bitmap b = new Bitmap(1, 1); Font fnt = new Font("Arial", i); Graphics graphics = Graphics.FromImage(b);
int width = (int)graphics.MeasureString(userName, fnt).Width; //Checking the width of the string with td width if (width < int.Parse(tdrun.Width.ToString())) { fntval = i.ToString(); break; } } return fntval; }
MeasureString() takes two arguments string and font size. This method belongs to graphics class. By making use of width property we will get the width of the string. After this we compare the calculated width with td width. If the Calculated width for the given string is less than the td width we will return that font value.Finally, For loop is used to limit the fontsize of the string between 48 and 10. This getfontsize() function will return larger fontsize value of the given username string that will fit into table cell.
|
| Author: Sebastian 13 Jun 2008 | Member Level: Gold Points : 1 |
This is very informative. Thanks for sharing the details.
|