Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine how wide a rendered character is in .NET

Tags:

c#

Lets say I render the character "A" to the screen with a size 14 font in Arial Regular. Is there a way in C# to calculate how many pixels wide it is?


The way I'm rendering text is through ESRI's ArcEngine which makes calls to GDI or GDI+ (I don't know which) in a round about fashion via the DynamicDisplay engine.

like image 870
patrick Avatar asked Nov 18 '10 21:11

patrick


4 Answers

It depends on the rendering engine being used. .NET may use GDI or GDI+. Switching can be done by setting the UseCompatibleTextRendering property accordingly or calling the Application.SetCompatibleTextRenderingDefault method.

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));

More details are described in this article:

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

Note that the above talks about Windows Forms. In WPF you would be using FormattedText

like image 181
Dirk Vollmar Avatar answered Nov 16 '22 07:11

Dirk Vollmar


Here's an MSDN piece about determining font metrics. You can use Graphics.MeasureString to do the measurement.

like image 4
spender Avatar answered Nov 16 '22 07:11

spender


You don’t say how you “render” it, but if you have a string, you can use MeasureString too.

like image 4
Martin Marconcini Avatar answered Nov 16 '22 07:11

Martin Marconcini


Graphics.MeasureString will get you the size in the current graphics units.

like image 3
plinth Avatar answered Nov 16 '22 09:11

plinth