C# – Measure String Width & Height (in pixels) Including Multi-line Text

A while back I posted a VB snippet of a simple way to measure text length in pixels. The below is a C# version, with some minor improvements (like not needing a form, so it’s okay to use with console and asp.net apps).

To measure a single line string:

//set font, size & style
Font f = new Font("Microsoft Sans Serif", 14, FontStyle.Regular);

//create a bmp / graphic to use MeasureString on
Bitmap b = new Bitmap(2200, 2200);
Graphics g = Graphics.FromImage(b);

//measure the string
SizeF sizeOfString = new SizeF();
sizeOfString = g.MeasureString("This is a text line", f);

//use:
Debug.WriteLine("String Height: " + sizeOfString.Height);
Debug.WriteLine("String Width: " + sizeOfString.Width);

This is a multi-line string – notice the addition of the width parameter:

//set font, size & style
Font f = new Font("Microsoft Sans Serif", 14, FontStyle.Regular);

//create a bmp / graphic to use MeasureString on
Bitmap b = new Bitmap(2200, 2200);
Graphics g = Graphics.FromImage(b);

//measure the string and choose a width:
SizeF sizeOfString = new SizeF();
sizeOfString = g.MeasureString("This is line 1" + Environment.NewLine + "This is line 2", f, 300);

//use:
Debug.WriteLine("String Height: " + sizeOfString.Height);
Debug.WriteLine("String Width: " + sizeOfString.Width);

For my examples, you’ll want to add the below to the top of your code:

using System.Diagnostics;
using System.Drawing;
C# – Measure String Width & Height (in pixels) Including Multi-line Text

2 thoughts on “C# – Measure String Width & Height (in pixels) Including Multi-line Text

  1. Uriel says:

    How do you know you dont really few lines in a multiline text?
    especially if we talk about a multiline textbox and just enough in advance so wide as to jump from row to automatic.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s