首页 > 解决方案 > g.drawString() 上的 Java“换行文本”+“自动字体大小”

问题描述

我已经有代码可以在 Rect 中将字符串居中。(来自另一个答案)

/**
     * 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”应该是字体大小 = 20px,“Hernandez”应该是字体大小 = 15px,“Republica Liberal Argentina”应该是字体大小 = 6px,并且在“Liberal”和“阿根廷”以适应 RECT。

我使用的矩形是:

new Rectangle(74,71,244,37)

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

欢迎任何帮助

标签: javagraphics2ddrawstringfontmetrics

解决方案


推荐阅读