MeasureString does not return exact width after rotation

506 views Asked by At

I'm using MeasureString method to calculate the width of text but the returned value is not exact. I'm using the following code for calculating text width

Size sz = g.MeasureString(text, font);
g.DrawString(text, font, brush, 
             new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat);
g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height));

This works fine without rotation. I'm using the following code to draw rotated text

g.RotateTransform(angle);
Size sz = g.MeasureString(text, font);
g.DrawString(text, font, brush, 
             new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat);
g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height));

The width value returned for second code snippet is different from first one and also it's not correct. See the following image

Additional space

At the bottom of the rectangle there is some additional space after text. The rectangle was drawn based on the width and height of the string so I think this has something to do with MeasureString method.

Please share your thoughts on avoiding this

Edit:

More space can be seen if text length is long (say 30 or more characters) .Rotation works fine for angles 0, 90, 180 and 270. Attached a screenshot

At 90 degree

0

There are 0 answers