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;
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.
LikeLike
Hum, good question – can you give me an example?
LikeLike
I understand that your example doesn’t get value in pixels
Is it possible?
LikeLike
These values are pixels I believe!
LikeLike