tags:

views:

119

answers:

3

Is there a way to measure the the amount of a string that will fit into a printed area without using the graphics object?

This is the only way i could find to do it:

Graphics instance = this.CreateGraphics();
instance.MeasureString(text, f, printArea1, StringFormat.GenericDefault, 
     out end, out lines);

I am using .net 2.0 and c# but I don't mind VB code.

+1  A: 

You can always approximate it yourself, but the basic analysis depends on knowing the relative widths of the different glyphs in the chosen typeface at various sizes.

Years ago I did this sort of thing in BASIC by constructing strings (runs of the same character) that would fill a fixed amount of space to come up with the approximation of space-per-character. With that information collected, you then iterate across your string accumulating the per-character width.

This is essentially what the graphic routines will do, but they're faster and more precise.

joel.neely
+2  A: 

The amount of space the string will take directly depends on the graphics object you want to render the string on.

Are you printing the string on the screen, a printer, a memory surface or a bitmap? What's the DPI of the surface you are trying to measure the text on? What unit? What space transformations need to be applied?

This all depends on System.Drawing.Graphics since it is the graphics object that keeps track of this information.

What are the reasons you don't want to use a Graphics object? If for some reason you are rendering to a non graphic object, you can always create one that fits as much as possible your other target and keep it for measuring.

Coincoin
+3  A: 

Yes, there is, in .NET 2.0

Size size = TextRenderer.MeasureString(this.Text, this.Font);

Martin
Thanks Martin, you saved my life. I was trying to use Graphics.Measurestring which required me to create a Form() and retrieve a Graphics instance. This is much cleaner. FYI, I found that the size you get with this method is NOT the same as Graphics.Measurestring.
Michael Dausmann