Click here to Skip to main content
13,343,221 members (58,243 online)
Click here to Skip to main content
Add your own
alternative version


88 bookmarked
Posted 14 Apr 2002

Bypass Graphics.MeasureString limitations

, 22 Apr 2003
Rate this:
Please Sign up or sign in to vote.
This sample code computes the width of the string, as drawn by Graphics.DrawString

Sample Image - measurestring.gif


Graphics.MeasureString can be used to compute the height and width of a text string. Often, however, the dimensions returned do not match the size of what gets drawn on screen when calling Graphics.DrawString. The red box above shows the dimensions returned by Graphics.MeasureString, which is about an em too wide...

The differences between what is computed and what is really drawn on the screen are related to how GDI+ computes its widths when using hinting and antialiasing. Here are the  gory details. A known work-around is to make GDI+ display its string antialiased, in which case the measured width matches the displayed result. If you want to draw standard strings (to match the GUI appearance, for instance), you are left out.

First, naive solution

The code I present here can be inserted into any class which needs to compute the real width of a string (shown by the yellow background above). The trick I use to compute the real string width is to ask GDI+ to draw the string into a bitmap and then find the position of the last character by reading back the pixels. A few optimisations ensure that this gets done as fast as possible (small bitmap, few pixels).

static public int MeasureDisplayStringWidth(Graphics graphics, string text,
                                            Font font)
    const int width = 32;

    System.Drawing.Bitmap   bitmap = new System.Drawing.Bitmap (width, 1, <BR>                                                                graphics);
    System.Drawing.SizeF    size   = graphics.MeasureString (text, font);
    System.Drawing.Graphics anagra = System.Drawing.Graphics.FromImage(bitmap);

    int measured_width = (int) size.Width;

    if (anagra != null)
        anagra.Clear (Color.White);
        anagra.DrawString (text+"|", font, Brushes.Black,
                           width - measured_width, -font.Height / 2);

        for (int i = width-1; i >= 0; i--)
            if (bitmap.GetPixel (i, 0).R != 255)    // found a non-white pixel ?

    return measured_width;

That's all, folks. Right-to-left scripts won't probably work with this piece of code.

Another solution...

It is also possible to get the accurate string geometry by using MeasureCharacterRanges, which returns a region matching exactly the bounding box of the specified string. This is faster and more elegant than the first solution I posted on CodeProject.

static public int MeasureDisplayStringWidth(Graphics graphics, string text,
                                            Font font)
    System.Drawing.StringFormat format  = new System.Drawing.StringFormat ();
    System.Drawing.RectangleF   rect    = new System.Drawing.RectangleF(0, 0,
                                                                  1000, 1000);
    System.Drawing.CharacterRange[] ranges  = <BR>                                       { new System.Drawing.CharacterRange(0, 
                                                               text.Length) };
    System.Drawing.Region[]         regions = new System.Drawing.Region[1];

    format.SetMeasurableCharacterRanges (ranges);

    regions = graphics.MeasureCharacterRanges (text, font, rect, format);
    rect    = regions[0].GetBounds (graphics);

    return (int)(rect.Right + 1.0f);

Post Script

Both functions only work with non-empty strings. The second solution will strip the trailing spaces; the first solution will take them in account. Choose the one which best fits your needs


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

Pierre Arnaud
Web Developer
Switzerland Switzerland

Pierre Arnaud got a Ph.D. in computer science at the Swiss Federal Institute of Technology; he currently works both as an independent contractor on hardware and software projects at OPaC bright ideas and as a senior software designer at EPSITEC.

Pierre was a key contributor to the Smaky computer, a real time, multitasking system based on the Motorola 680x0 processor family.

Now, Pierre works on his spare time for the Creative Docs .NET project: it is a vector based drawing and page layout software based on .NET and AGG.

You may also be interested in...

Comments and Discussions

GeneralDoes Not Work For Hypertext Label Pin
nbk33r126-Jul-05 17:24
membernbk33r126-Jul-05 17:24 
Generalcode seems to work but i have some strange result :( Pin
Sn3b11-Jul-05 23:10
memberSn3b11-Jul-05 23:10 
GeneralStill not correct with special strings!!! Pin
Anonymous21-Jun-05 18:49
sussAnonymous21-Jun-05 18:49 
GeneralGraphics argument Pin
Anonymous1-Jun-05 6:07
sussAnonymous1-Jun-05 6:07 
GeneralRe: Graphics argument Pin
Pierre Arnaud1-Jun-05 20:52
memberPierre Arnaud1-Jun-05 20:52 
QuestionRe: Graphics argument Pin
Steven Rothwell22-Feb-09 15:31
memberSteven Rothwell22-Feb-09 15:31 
QuestionIs this a bug? Pin
Matthew Hayhurst18-May-05 4:54
sussMatthew Hayhurst18-May-05 4:54 
AnswerRe: Is this a bug? Pin
Pierre Arnaud18-May-05 20:43
memberPierre Arnaud18-May-05 20:43 
The code scans the pixels, that's right. But it adds an additional vertical bar at the end of the text; it then looks for the last pixels in the image, which will be those of that additional character. So everything should just work Smile | :)

GeneralVery helpful Pin
smushkat4-Mar-05 18:50
susssmushkat4-Mar-05 18:50 
GeneralNumber of lines text wrapped. Pin
johannf21-Feb-05 7:16
memberjohannf21-Feb-05 7:16 
GeneralC code Pin
acostein4-Feb-05 19:46
memberacostein4-Feb-05 19:46 
GeneralA (possible) imrovement Pin
xaverbirrer5-May-05 5:48
memberxaverbirrer5-May-05 5:48 
Generalhighlighting Pin
sreejith ss nair27-Dec-04 22:28
membersreejith ss nair27-Dec-04 22:28 
QuestionWhat about Height Problem? Pin
Sameers (theAngrycodeR )11-Jul-04 13:57
memberSameers (theAngrycodeR )11-Jul-04 13:57 
Questionrect.Right + 1.0f? Pin
imessvb3-Jun-04 23:02
memberimessvb3-Jun-04 23:02 
GeneralParameter Pin
Ratee29-May-04 20:33
memberRatee29-May-04 20:33 
GeneralRe: Parameter Pin
Pierre Arnaud29-May-04 23:19
memberPierre Arnaud29-May-04 23:19 
GeneralA little correction Pin
edx_fa25-Jan-04 12:52
memberedx_fa25-Jan-04 12:52 
GeneralRe: A little correction Pin
Pierre Arnaud25-Jan-04 19:43
memberPierre Arnaud25-Jan-04 19:43 
GeneralPoor Pin
Gensi22-Aug-03 3:26
sussGensi22-Aug-03 3:26 
GeneralRe: Poor Pin
Pierre Arnaud22-Aug-03 3:33
memberPierre Arnaud22-Aug-03 3:33 
GeneralRe: Poor Pin
Anonymous22-Aug-03 7:32
sussAnonymous22-Aug-03 7:32 
GeneralRe: Poor Pin
Gensi22-Aug-03 7:33
sussGensi22-Aug-03 7:33 
GeneralIts not Poor, its helpful Pin
xaverbirrer5-May-05 4:30
memberxaverbirrer5-May-05 4:30 
GeneralGREAT Pin
jlau13-Mar-03 23:05
sussjlau13-Mar-03 23:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 23 Apr 2003
Article Copyright 2002 by Pierre Arnaud
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid