所以对于我正在开发的一个塔防御游戏,我想要有一个带有文本的精灵,塔是防御的。然而,这个精灵内部的文本需要根据它所受到的伤害进行更改。我有点书呆子气,需要精确的X和Y来绘制字符串,以便它在图像中居中。
如何找到字符串的高度,以便可以相应地调整绘制的字符串的Y元素?
g.setColor(new Color(Integer.parseInt(tObj[0].toString())));
g.drawString(String.format("Wave: %d", getWave()), 5, 460);发布于 2015-06-03 23:34:01
假设二维矩形,其左上角为point.x,point.y坐标,具有width宽度和height高度。当我需要在矩形的中心绘制一个字符串时,我使用了这个。
String text = "Centered Text";
FontMetrics fontMetrics = graphics.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(text, graphics);
int x = point.x + (width - (int) rect.getWidth()) / 2;
int y = point.y + (height - (int) rect.getHeight()) / 2 + fontMetrics.getAscent();
graphics.drawString(text, x, y);https://stackoverflow.com/questions/30624305
复制相似问题