I have a region in my JPanel bounded by the point (0,0) and (width,height). It is a square.
I have a word
String s;
I’d like to find the maximum font size that I can use for s. Now, I know there is a way to do it using FontMetrics and making a for loop to keep increasing the size of the font until it doesn’t fit inside the region. But this is SO inefficient and there must be a way to compute the font size of a given font type, such as “Courier” that will fit in this region.
Example of BAD way:
Font f = new Font("Courier", Font.PLAIN, 1);
FontMetrics fm = this.getFontMetrics(f); //this is a JPanel
do {
f = new Font("Courier", Font.PLAIN, f.getSize()+1);
fm = this.getFontMetrics(f);
while(fm.stringWidth(s) < width && fm.getHeight() < height);
I had the same problem and found a solution that is a little bit optimized, compared to just iterating over all font sizes. I try to converge towards the optimal font size by adjusting diffs that I either add or subtract until I find a diff font size below 1.
I have tried that with different resolutions of the image and the sizes of the font. It takes 10 to 12 iterations until a font is found that will fit the max rectangle. I hope it will be helpful to somebody.