How to determine the size of a string given a font
Asked Answered
E

4

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?

Espousal answered 6/4, 2009 at 12:14 Comment(0)
H
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

Hutchison answered 6/4, 2009 at 12:22 Comment(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))Clodhopping
J
6

How about this:

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

(Here is the MSDN link.)

Juggle answered 6/4, 2009 at 12:18 Comment(0)
C
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);
Cumbrous answered 15/6, 2021 at 2:48 Comment(0)
A
0

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

Austro answered 6/4, 2009 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.