Aaron
Aaron

Reputation: 846

Center en resize String on a rectangle

I'm painting a rectangle on which I draw a String. This String should be centered (that works) but also resized so "all" Strings fit on this rectangle.

The centering works but I'll include it anway so this question might help other people who want to center and resize Strings on rectangles.

The problem is that the While loop is infite. The Rectangle2D always has the same size...

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    ... other paintings ...

    Font font = new Font("Courier new", Font.BOLD, MAX_FONTSIZE);

    // resize string
    Rectangle2D fontRec = font.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
    while(fontRec.getWidth() >= width  * 0.95f || fontRec.getHeight() >= height  * 0.95f){
        Font smallerFont = font.deriveFont((float) (font.getSize() - 2));
        g2.setFont(smallerFont);
        fontRec = smallerFont.getStringBounds(information, 
        g2.getFontMetrics().getFontRenderContext());
    }

    // center string
    FontMetrics fm = g2.getFontMetrics();
    float stringWidth = fm.stringWidth(information);
    int fontX = (int) (x + width / 2 - stringWidth / 2);
    int fontY = (int) (y + height / 2);
    g2.drawString(information, fontX, fontY);
}

The correction is:

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

        ... other paintings ...

    // resize string
    Rectangle2D fontRec = font.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
    while(fontRec.getWidth() >= width  * 0.95f || fontRec.getHeight() >= height  * 0.95f){
        Font smallerFont = font.deriveFont((float) (font.getSize() - 2));
        font = smallerFont;
        g2.setFont(smallerFont);
        fontRec = smallerFont.getStringBounds(information, g2.getFontMetrics().getFontRenderContext());
    }

    // center string
    FontMetrics fm = g2.getFontMetrics();
    float stringWidth = fm.stringWidth(information);
    int fontX = (int) (x + width / 2 - stringWidth / 2);
    int fontY = (int) (y + height / 2);
    g2.drawString(information, fontX, fontY);

}

This code centers and resizes strings properly.

Upvotes: 2

Views: 356

Answers (1)

You never update font, smallerFont itself remains the same value throughout the loop.

Upvotes: 1

Related Questions