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;