How can I center Graphics.drawString() in Java?

前端 未结 3 2241
忘了有多久
忘了有多久 2020-12-14 00:45

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

3条回答
  •  无人及你
    2020-12-14 01:30

    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);
    

提交回复
热议问题