在 Java Graphics2D 中,文本如何在矩形上居中对齐?

IN Java Graphics2D, how can text be center aligned on a Rectangle?

我在这段代码中,我有一个 window,其中一个角有一个蓝色框。

我需要让文本在此框上居中对齐。

public class drawComponent extends JComponent {
public void paintComponent(Graphics g){ //called on window update
    int clueHeightDiff= 0;
    int gap = 5;
    int border = 10;
    Font font = new Font("Ariel", Font.PLAIN, 30);
Color blue = new Color(0,0,255);
Color white = new Color(255,255,255);

int winH = Jeopardy.window.getBounds().getSize().height;
int winW = Jeopardy.window.getBounds().getSize().width;
int width = (winW - ((2 * border) + (5 * gap))) / 6 ;
int height = ((winH - ((4*border) + (5 * gap) + clueHeightDiff ))) / 6;
int clueHeight = height + clueHeightDiff;
int Fx = border + (5* width) + (5*gap);
int foY = border + (2*gap) + (2*height) + clueHeightDiff;
Rectangle F2 = new Rectangle(Fx,foY, width , height);
Graphics2D g2f2 = (Graphics2D) g;
g2f2.draw(F2);
g2f2.fill(F2);
g2f2.setColor(blue);
FontMetrics metrics = g2f2.getFontMetrics(font);
    int height = metrics.getHeight();
    int width = metrics.stringWidth(text);
    Dimension size = new Dimension(width+2, height+2);

鉴于此框的 X 和 Y 边界,我需要文本能够舒适地放入其中。根据 documentation,stringwidth() returns 只有第一个字符的值,我只是找不到有效的方法。

FontMetrics#stringwidth 通常会 return 渲染文本所需的像素数量

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane(new Rectangle(150, 150, 50, 50)));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Rectangle boxIn;

        public TestPane(Rectangle boxIn) {
            this.boxIn = boxIn;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String text = "Hello";
            FontMetrics fm = g2d.getFontMetrics();

            int x = boxIn.x + ((boxIn.width - fm.stringWidth(text)) / 2);
            int y = boxIn.y + (((boxIn.height - fm.getHeight()) / 2) + fm.getAscent());

            g2d.setColor(Color.BLUE);
            g2d.fill(boxIn);
            g2d.setColor(Color.WHITE);
            g2d.drawString(text, x, y);

            g2d.dispose();
        }

    }

}

您也可以使用 TextLayout,这有点复杂,但会为您提供一个边界框,表示呈现文本所需的区域。这对属性文本更有用,但仍然有用