Java – you need a way to scale fonts to fit rectangles

I just wrote some code to scale the font to fit a rectangle It starts at 18 wide and repeats until it fits

It seems very inefficient, but I can't find a non - circular way to do it This line is used to scale the labels in the game grid, so I can't see the solution (packaging, cutting and extending over the rectangle are unacceptable)

It's actually fast. I'm doing this for hundreds of rectangles. It's fast enough to slow it down

If no one comes up with anything better, I just load a table to start guessing (so it's closer than 18) and use this - except for its great lag in engineering

public Font scaleFont(String text,Rectangle rect,Graphics g,Font pFont) {
    float nextTry=18.0f;
    Font font=pFont;

    while(x > 4) {                             
            font=g.getFont().deriveFont(nextTry);
            FontMetrics fm=g.getFontMetrics(font);
            int width=fm.stringWidth(text);
            if(width <= rect.width)
                return font;
            nextTry*=.9;            
    }
    return font;
}

Solution

Semi pseudo code:

public Font scaleFont(String text,Font pFont) {
    float fontSize = 20.0f;
    Font font = pFont;

    font = g.getFont().deriveFont(fontSize);
    int width = g.getFontMetrics(font).stringWidth(text);
    fontSize = (rect.width / width ) * fontSize;
    return g.getFont().deriveFont(fontSize);
}

I don't know why you didn't pass pfont?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>