The System.Drawing.Graphics MeasureString aligns the line width with a few extra pixels (I don’t know why), so measuring the width of one character of a fixed length and then dividing it by the maximum width gives an estimate of the number of characters that can fit into the maximum width.
To get the maximum number of characters, you need to do something iterative:
using (Graphics g = this.CreateGraphics()) { string s = ""; SizeF size; int numberOfCharacters = 0; float maxWidth = 50; while (true) { s += "a"; size = g.MeasureString(s, this.Font); if (size.Width > maxWidth) { break; } numberOfCharacters++; }
Update : You will learn something new every day. Graphics.MeasureString (and TextRenderer) fills the borders with a few extra pixels to place overhanging glyphs. It makes sense, but it can be annoying. Cm:
http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx
Sounds like the best way to do this:
using (Graphics g = this.CreateGraphics()) { g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; SizeF size = g.MeasureString("a", this.Font, new PointF(0, 0), StringFormat.GenericTypographic); float maxWidth = 50;
source share