5

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.

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • `MeasureString` with several different font point sizes and select the best one. – Oded Apr 30 '12 at 11:05
  • So its trial and error? Im drawing lots of strings.. of different sizes, surely measuring many times for each one isnt the best way? – IAmGroot Apr 30 '12 at 11:06
  • 1
    It isn't efficient, but if you start with a reasonable size (possibly derived from the width in pixels), you can minimize trials. – Oded Apr 30 '12 at 11:08
  • I've done your suggestion in a while Loop. Ever increasing font size til it becomes bigger than desired width. It works good considering :) Thanks. – IAmGroot Apr 30 '12 at 11:18
  • The [answer](http://stackoverflow.com/a/10382725/1583) from @John Koerner has an interesting idea - using the ratio of the width/height of one `MeasureString` in order to determine an optimal size. – Oded Apr 30 '12 at 11:21

1 Answers1

4

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.

stuartd
  • 70,509
  • 14
  • 132
  • 163
John Koerner
  • 37,428
  • 8
  • 84
  • 134