I\'m currently working on the menu system for my Java game, and I wonder how I can center the text from Graphics.drawString(), so that if I want to dra
I did create a function to keep the text in center of the image
private static void setTextCenter(Graphics2D graphics2DImage, String string,
BufferedImage bgImage) {
int stringWidthLength = (int)
graphics2DImage.getFontMetrics().getStringBounds(string, graphics2DImage).getWidth();
int stringHeightLength = (int)
graphics2DImage.getFontMetrics().getStringBounds(string, graphics2DImage).getHeight();
int horizontalCenter = bgImage.getWidth() / 2 - stringWidthLength / 2;
int verticalCenter = bgImage.getHeight() / 2 - stringHeightLength / 2;
graphics2DImage.drawString(string, horizontalCenter, verticalCenter);
}
where, graphics2DImage is.
Graphics2D graphics2DImage = bgImage.createGraphics();
graphics2DImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
graphics2DImage.drawImage(bgImage, 0, 0, null);