Last post Feb 23, 2011 02:29 PM by BaconEggAndCheeseSandwich
Feb 23, 2011 10:22 AM|BaconEggAndCheeseSandwich|LINK
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))
font = new Font(fontFamily, fontSize, FontStyle.Regular);
textSize = graphic.MeasureString(text, font);
graphic.SmoothingMode = SmoothingMode.AntiAlias;
graphic.DrawString(text, font, Brushes.Black, rect);
Feb 23, 2011 01:22 PM|SGWellens|LINK
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.
Feb 23, 2011 02:29 PM|BaconEggAndCheeseSandwich|LINK
Thanks for the reply!
Unfortunately, I cannot provide an alternative view of the text because I'm writing to an image with confined areas designated for text. I need to write the information from the form to the image, but would like to prevent the user from entering too much
text that it won't fit in the rectangle.
Maybe the problem I was having trouble solving with determining the maximum allowed characters arose from using a proportional font. If I switch to a non-proportional font (you suggested Courier), then I could more accurately measure the size of the text.
I'll try swapping the font-family and come back with my results.