20

I have a small form that displays some progress information.
Very rarely I have to show a rather long message and I want to be able to resize this form when needed so that this message fits in the form.

So how do I find out how wide string S will be rendered in font F?

Nifle
  • 11,745
  • 10
  • 75
  • 100

4 Answers4

21

It depends on the rendering engine being used. You can basically switch between GDI and GDI+. Switching can be done by setting the UseCompatibleTextRendering property accordingly

When using GDI+ you should use MeasureString:

string s = "A sample string";

SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));

When using GDI (i.e. the native Win32 rendering) you should use the TextRenderer class:

SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));

See this article: Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • 1
    If you're using WPF and need a variable FontSize, make sure to convert from pixels to points `points = (pixels * (72.0 / 96.0))` – Slate Oct 15 '18 at 10:36
6

How about this:

Size stringsize = graphics.MeasureString("hello", myFont);

(Here is the MSDN link.)

G S
  • 35,511
  • 22
  • 84
  • 118
2

For this answer I use a helper function:

private static double ComputeSizeOfString(string text, string fontFamily, double fontSize)
{
      System.Drawing.Font font = new(fontFamily,  (float)fontSize);
      System.Drawing.Image fakeImage = new System.Drawing.Bitmap(1, 1);
      System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(fakeImage);
      return graphics.MeasureString(text, font).Width;
}

So basically the method uses a fakeimage with dimensions (1,1) to compute the length of the string, in this case the width of the image created from your chosen text.

An example of how to use it ends up like this:

string myTxt = "Hi there";
double szs = ComputeSizeOfString(myTxt, "Georgia", 14);
Pepe Alvarez
  • 1,218
  • 1
  • 9
  • 15
0

Back in the Win32 I was using the equivalent for VisualStyleRenderer::GetTextExtent function for this.

bernhardrusch
  • 11,670
  • 12
  • 48
  • 59