Need a way to scale a font to fit a rectangle

前端 未结 6 1272
耶瑟儿~
耶瑟儿~ 2021-01-01 19:46

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 ineffic

6条回答
  •  余生分开走
    2021-01-01 20:33

    You could use interpolation search:

    public static Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
        float min=0.1f;
        float max=72f;
        float size=18.0f;
        Font font=pFont;
    
        while(max - min <= 0.1) {
            font = g.getFont().deriveFont(size);
            FontMetrics fm = g.getFontMetrics(font);
            int width = fm.stringWidth(text);
            if (width == rect.width) {
                return font;
            } else {
                if (width < rect.width) {
                    min = size;
                } else {
                    max = size;
                }
                size = Math.min(max, Math.max(min, size * (float)rect.width / (float)width));
            }
        }
        return font;
    }
    

提交回复
热议问题