# Accurately calculating the max characters for a font within the bounds of a rectangleRSS

## 2 replies

Last post Feb 23, 2011 02:29 PM by BaconEggAndCheeseSandwich

• ### Accurately calculating the max characters for a font within the bounds of a rectangle

Greetings,

I have an image that I'm writing text to. I have calculated the coordinates of the fields on the image where I am applying the text entered through a webform. Currently, if the TextSize is greater than the Rectangle Size, I reduce the size of the font until they fit. The problem that I will run into later on is an infinite loop when the size of the text cannot be reduced anymore and is still larger than the bounds of the rectangle. Before that occurs, I would like to have a way of getting the maximum allowed characters that can possibly fit into the field, constrained by a reasonably sized font.

Can anyone help me figure out the math for calculating this? Or is there some .NET functionality I could use that I'm simply not aware of?

Here is the function I'm using to write text onto an image:

```private void WriteToBondImage(Image img, string text, FormFieldPosition ffp)
{
var graphic = Graphics.FromImage(img);
var p = new Point(ffp.StartX, ffp.StartY);
var s = new Size(ffp.EndX - ffp.StartX, ffp.EndY - ffp.StartY);
var rect = new Rectangle(p, s);

var fontFamily = new FontFamily(FontFamily.GenericSerif.Name);
var fontSize = 12;
var font = new Font(fontFamily, fontSize, FontStyle.Regular);
var textSize = graphic.MeasureString(text, font);
StringFormat sf = new StringFormat(StringFormatFlags.NoClip);

while ((textSize.Width + textSize.Height) > (rect.Width + rect.Height))
{
fontSize--;
font.Dispose();
font = new Font(fontFamily, fontSize, FontStyle.Regular);
textSize = graphic.MeasureString(text, font);
}

graphic.SmoothingMode = SmoothingMode.AntiAlias;
graphic.DrawString(text, font, Brushes.Black, rect);
graphic.Dispose();
}```
• SGWellens

All-Star

124328 Points

10142 Posts

Moderator

### Re: Accurately calculating the max characters for a font within the bounds of a rectangle

The problem is that with a proportional font you can fit many i's in a line but only a few w's.  So there is no count you can reliable calculate.

The width of the letter m is generally considered to be the average width of a character in a given font.

With a non-proprotional font (like courier) any letter can be used.

I would strive to have an alternate display of the text like in a status field, a tool-tip window, an elipse(...) buttton to display the remaining text, etc.

Steve Wellens

My blog