Doomsknight Doomsknight - 1 year ago 95
C# Question

C# calculate the height of a string in with the given width

Im trying to write text in C# so that it spans the required width (approximately).

To write text you need to specify the height. So I need to know what height would make it write to the desired length.

Font myFont = new Font(FontFamily.GenericSansSerif, unknown);
gc.DrawString(LabelText, myFont, gBrush, 0, 0);

Ive found the following, but it requires FONT, which requires height. Which defeats the whole point?

gc.MeasureString(LabelText, new Font(FontFamily.GenericSansSerif, 12), length);

How would I determine the required height to make for example "I am a String" stretch 50px.

Answer Source

There is an example on the site switchonthecode (note - archived version). They provide a method that takes a minimum and maximum font size along with the size of your area. It tries the minimum size and from there determines the ratio of the font and then determines the best size for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download