Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
IAmGroot Avatar asked Oct 07 '22 23:10

IAmGroot


1 Answers

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.

like image 161
John Koerner Avatar answered Oct 13 '22 12:10

John Koerner