0

Hello i'm currently working on a 2D Game Engine written entirely in java. Is there a way to centre a Graphics Object (g.drawString(x,y,z).

It would be preferably if this could be done through Graphics and the DefaultToolkit.

Thankyou very much :)

DaForce
  • 1
  • 2
  • 1
    Start by taking a look at [this](http://stackoverflow.com/questions/14284754/java-center-text-in-rectangle/14287270#14287270) – MadProgrammer Jul 03 '13 at 06:27
  • string are measured by points, while you draw with pixels, and there is no way to draw a string in pixels, but you would get the drawn string in pixel and draw it at the center –  Jul 03 '13 at 06:28
  • Yes you could center a graphics object. What are you trying to achieve here. `g.drawString(x,y,z)` does it for you. You need to if other objects could be centered aswell? – blganesh101 Jul 03 '13 at 06:30
  • So if i use g.drawString(x,y,z) and for example y (x axis) is 40, would the start of the text be located at 40px or would the centre of the text be at 40px? – DaForce Jul 03 '13 at 06:32

1 Answers1

1

Simple mathematics. We have the object to be centered and the area where it should be centered.

Object width - w

Object height - h

Area width - aW

Area height - aH

//Follow center coordinates are coordinates where top left corner should be placed in order for the object to lie in center

centerWidth = (aW - W) /2

centerHeight = (aH - H) /2

As you can see, you MUST know the metrics of area you are placing your object on ! If that area is just the screen, then screen dimension can be used like this.

    //Some dummy object metrics
    int w = 30;
    int h = 60;

    //Now we find out the area metrics
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int aW = screenSize.width;
    int aH = screenSize.height;

    //Apply our common formula
    int centerWidth = (aW - w) / 2;
    int centerHeight = (aH - h) /2;

This works well for objects you know (their width and height).

Text centering

If you want to center text, you can use FontMetrics class, which allows you to measure size of text.