Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the size of a string given a font

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?

like image 969
Nifle Avatar asked Apr 06 '09 12:04

Nifle


People also ask

How do you tell what size a font is?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.

How do you find the text size in Python?

Python has a method called len() that gives us the length of any composite object. To get the length of a string, just pass the string to the len() call.

How do I get font size in HTML?

if the html element has inline style, you can using the . style. fontSize to get the font-size!


1 Answers

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

like image 142
Dirk Vollmar Avatar answered Oct 12 '22 14:10

Dirk Vollmar