简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM