Tenebris
Tenebris

Reputation: 83

Having trouble to center text on a Graphics2D element

Hi I am building a replica of the game 2048 the game works but I have trouble keeping my numbers in the middle of the tiles. Basically everything is in order for numbers that are under 32 but the more they go up the more they shift to the bottom left.

First is the input that I use and than the class. While the g is the Graphics2D element which represents the tile.

int getX= WIDTH/2- Text.textWidth(""+value, font, g)/2;
int getY= HEIGHT/2+ Text.textHeight(""+value, font, g)/2;
g.drawString(""+value, getX, getY);

public class Text {
private Text(){
}

public static int textHeight(String out, Font font, Graphics2D g){
    g.setFont(font);
    Rectangle2D bounds=g.getFontMetrics().getStringBounds(out, g);
    return (int)bounds.getWidth();
}
public static int textWidth(String out,Font font, Graphics2D g){
    g.setFont(font);
    if(out.length()==0)
        return 0;
    TextLayout tl=new TextLayout(out,font,g.getFontRenderContext());
    return (int)tl.getBounds().getHeight();
}

}

Upvotes: 0

Views: 39

Answers (1)

David Gilbert
David Gilbert

Reputation: 4477

Your textHeight() method returns the width of the string bounds, and the textWidth() method returns the height of the string bounds. Isn't that the wrong way around?

Upvotes: 1

Related Questions