I just wrote some code to scale a font to fit within (the length of) a rectangle. It starts at 18 width and iterates down until it fits.
This seems horribly inefficient, but I can't find a non-looping way to do it. This line is for labels in a game grid that scales, so I can't see a work-around solution (wrapping, cutting off and extending past the rectangle are all unacceptable).
It's actually pretty quick, I'm doing this for hundreds of rectangles and it's fast enough to just slow it down a touch.
If nobody comes up with anything better, I'll just load the starting guess from a table (so that it's much closer than 18) and use this--except for the lag it works great.
public Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
float try=18.0f;
Font font=pFont;
while(x > 4) {
font=g.getFont().deriveFont(try);
FontMetrics fm=g.getFontMetrics(font);
int width=fm.stringWidth(text);
if(width <= rect.width)
return font;
try*=.9;
}
return font;
}