0

您好,我目前正在开发一个完全用 java 编写的 2D 游戏引擎。有没有办法使图形对象居中(g.drawString(x,y,z)。

如果这可以通过 Graphics 和 DefaultToolkit 完成,那就更好了。

非常感谢 :)

4

1 回答 1

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.

于 2013-07-03T06:35:52.257 回答