views:

135

answers:

2

I use this code for drawing text in a panel:

Graphics g = panel1.CreateGraphics();
g.DrawString(...);

So I want to know what size the input text will be when rendered in the panel.

+6  A: 

Use g.MeasureString() to get the width of a string in the grapic context.

// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);
Obalix
Nice, this is new to me.
Finglas
A couple of points I'd like to clean up: 1) = new SizeF(); is unnecessary here; 2) it's good practice to dispose fonts (and many other graphical objects) like stringFont.Dispose() or use "using" statement.
Zenya
A: 

You can also use TextRenderer.MeasureText which is sometimes easier to use than MeasureString.

Nick
But is only accurate if you use TextRenderer.DrawText
Eric