Need a way to scale a font to fit a rectangle

前端 未结 6 1240
耶瑟儿~
耶瑟儿~ 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:32

    Change all width variables to float instead of int for better result.

    public static Font scaleFontToFit(String text, int width, Graphics g, Font pFont)
    {
        float fontSize = pFont.getSize();
        float fWidth = g.getFontMetrics(pFont).stringWidth(text);
        if(fWidth <= width)
            return pFont;
        fontSize = ((float)width / fWidth) * fontSize;
        return pFont.deriveFont(fontSize);
    }
    

提交回复
热议问题