Reputation: 11923
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
?
Upvotes: 20
Views: 18430
Reputation: 1624
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);
Upvotes: 2
Reputation: 176169
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
Upvotes: 21
Reputation: 11890
Back in the Win32 I was using the equivalent for VisualStyleRenderer::GetTextExtent function for this.
Upvotes: 0