微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

g.drawString() 上的 Java“换行文本”+“自动字体大小”

如何解决g.drawString() 上的 Java“换行文本”+“自动字体大小”

我已经有了在 Rect 中将 String 居中的代码。 (来自另一个答案)

/**
     * Draw a String centered in the middle of a Rectangle.
     *
     * @param g The Graphics instance.
     * @param text The String to draw.
     * @param rect The Rectangle to center the text in.
     */
    public void drawCenteredString(Graphics g,String text,Rectangle rect,Font font) {
        // Get the FontMetrics
        FontMetrics metrics = g.getFontMetrics(font);
        // Determine the X coordinate for the text
        int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
        // Determine the Y coordinate for the text (note we add the ascent,as in java 2d 0 is top of the screen)
        int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
        // Set the font
        g.setFont(font);
        g.setColor(new Color(0xff5b3a20));
        // Draw the String
        g.drawString(text,x,y);
        
        g.dispose();
    }

我现在需要的是一种根据 RECT 宽度和高度自动调整字体大小的方法。 此外,如果可能,请使用填充。

示例:

String str1 = "Cena"
String str2 = "Hernandez"
String str3 = "Republica Liberal Argentina"

我需要一些方法来确定“Cena”应该是 Font Size = 20px,“Hernandez”应该是 Font Size = 15px 并且“Republica Liberal Argentina”应该是 Font Size = 6px 并且在“Liberal " 和 "Argentina" 以适应 RECT。

我使用的矩形是:

new Rectangle(74,71,244,37)

如果您需要,我可以提供任何代码

欢迎任何帮助

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。