Determining the maximum number of characters that may be displayed within a given area RRS feed

  • Question

  • Hi all,

    I'm looking for a way to determine, for a given font, a "conservative" maximum number of characters that I can display in a given field using that font.

    I know that I can use Graphics.MeasureString() to figure out the size of a specific string.  Instead, I want to know, "a lower bound on the maximum number of characters of a given font that can be displayed within a given area, without being truncated." 

    Obviously, I say "lower bound", because I will be dealing with variable-width fonts.

    So the hypothetical API I'm looking for is something like:

    int GetMaxLength(Font font, SizeF size);

    I could probably look at writing something like this myself, but before I do, I thought I would ask here and see if something like this exists already.

    I need this code for a .NET Compact Framework application, though I'm happy to translate from the desktop Framework or Win32, as needed....


    Andrew Brown

    Thursday, February 16, 2006 3:27 AM


  • I believe someone asked this very question a while back on the forums.  The final verdict was that there was no such method available but creating one wouldn't be too difficult.  The problem is that the maximum number of characters that fit within a region is completely dependent upon the font used and the characters in the text.  A "W" takes up more space than an "i" an consequently you might be able to fit 20 "i"s on a line but only 15 "W"s.

    The general guideline people use when trying to fit a string into a region is to start with a reasonable # of characters and then truncate characters until it fits or add characters until it doesn't.  It is inefficient but it works.  If you assume that most of the time your string will fit then use the entire string and then backtrack as needed until MeasureString returns a value that is within the range you want.  Given your assumption the performance will be good in the general case.

    If you really just care about how many characters you might be able to fit in a region then worse-case would be with n "W"s while a best-case would be n "I"s.  You could build a string of each and use MeasureString to find the optimal character count.

    Michael Taylor - 2/16/06

    Thursday, February 16, 2006 2:59 PM