4

This is the inverse of Determine Label Size based upon amount of text and font size in Winforms/C#.

Given a rectangle of fixed height but variable width, is there an efficient way to determine the largest size of a given font that will fit in the rectangle (height-wise) without risk of losing ascenders/descenders?

I'm currently considering iterative use of MeasureString() to find the best font size but wonder if there's a better way.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553

2 Answers2

2

I've never found a better way to do it than using MeasureString iteratively. You can optimise by jumping in increments.

WPF has some nicer text sizing options, though it feels like rubbing salt in the wound.

Tristan Warner-Smith
  • 9,631
  • 6
  • 46
  • 75
  • 1
    I went with this and it works well enough. Yeah, too bad the target audience is very slow to update .NET versions... – Eric J. Oct 02 '09 at 13:21
2

You don't really need iterations. Since the total width is also proportional to the font size, you only have to measure the string once with any reasonable sized font. Afterwards, you can calculate your required font size:

fontSizeUsedToMeasure*(RectangleWidth/MeasuredWidth)(*0.8 for a nicer fit)
Peter O.
  • 32,158
  • 14
  • 82
  • 96
kris
  • 21
  • 2