ELM
ELM

Reputation: 529

C# String Measurements

I want to measure the length of a string into pixel units. I searched the web for 2 days but got no luck. Finally, I found some code snippet a few minutes ago from a blog and modified it a little bit. Here's my function:

private void cmdMeasure_Click(object sender, EventArgs e)
{
    Font fntStyle = new Font("Arial", 16, FontStyle.Regular, GraphicsUnit.Pixel);
    Size textSize = TextRenderer.MeasureText(str2measure.Text, fntStyle);
    MessageBox.Show(textSize.ToString());
}

Question:

What is the unit of 16? Is it em, pt, or the unit of GraphicsUnit enum? I don't really get the description defined by c# "the em-size of the new font in the units specified by the unit parameter."

Does the TextRenderer.MeasureText method include the spaces between the characters in its measurement?

Upvotes: 2

Views: 2652

Answers (3)

Shaikh Farooque
Shaikh Farooque

Reputation: 2640

Ans Q1. It is pixels only as you are passing GraphicsUnit.Pixel

Ans Q2. It is considering the entire text block no matter what is the content even white spaces.

Upvotes: 0

Larsenal
Larsenal

Reputation: 51156

What is the unit of 16? Is it em, pt, or the unit of GraphicsUnit enum? I don't really get the description defined by c# "the em-size of the new font in the units specified by the unit parameter."

As others have said, it's pixels since you pass GraphicsUnit.Pixel.

Does the TextRenderer.MeasureText method include the spaces between the characters in its measurement?

Yes. It gives you the dimensions of the bounding box around the whole block of text.

Upvotes: 3

Brad Rem
Brad Rem

Reputation: 6026

TextRenderer.MeasureString does take in account the spaces. In your example, the number 16 is in pixels.

Although, I'm not sure you are measuring your string correctly. I think you need to get your Font from your str2measure textbox:

Size textSize = TextRenderer.MeasureText(str2measure.Text, str2measure.Font);

Upvotes: 1

Related Questions