Calculate the Display Width of a String in C#

Calculate the display width of a string in C#?

You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.

For WinForms: Graphics.MeasureString

For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...

How to find string's width in C# (in pixels)

Use Graphics.MeasureString()

From MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

private void MeasureStringMin(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);

// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}

How to determine width of a string when printed?

Yes, you can use MeasureString from the Graphics class

This method returns a SizeF structure that represents
the size, in the units specified by
the PageUnit property, of the string
specified by the text parameter as
drawn with the font parameter.

private void MeasureStringMin(PaintEventArgs e)
{

// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);

// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}

How do you calculate pixel size of string?

I think you need to create a textblock in code and assign the desired text to it. Then you can get the actual height and width from it. See the below code

         TextBlock txt=new TextBlock();
//set additional properties of textblock here . Such as font size,font family, width etc.
txt.Text = "your text here";
var height = txt.ActualHeight;
var width = txt.ActualWidth;

You can do further operations based on this height and width

I am not saying this is the optimized solution .But this will work for you

How to get width and height of string on the screen?

The easy answer is Graphics.MeasureString. But it's rather infamous for not being particularly accurate. If you need better accuracy you can check out this article: Using MeasureCharacterRanges to Draw Text.



Related Topics



Leave a reply



Submit