如何在java中水平拉伸文本

时间:2013-02-03 08:40:55

标签: java swing graphics

  

可能重复:
  How to resize text in java

是否可以水平拉伸java中的文本。我知道应该在那里,但我无法弄明白。字体大小会影响文本的高度和宽度。我尝试使用FontMetrics,但它只给出了文本的宽度。但是我只需要改变文本宽度,使其看起来好像被拉伸了一样。

如果有人知道这样做,请告诉我。 在此先感谢。

1 个答案:

答案 0 :(得分:4)

可能还有其他方法可以实现相同的结果,例如将文本转换为形状并使用AffineTransformation,但这是一个可以实现的结果......

enter image description here

public class StretchText {

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

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

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage imgTet;

        public TestPane() {
            Font font = UIManager.getFont("Label.font");
            FontMetrics fm = getFontMetrics(font);
            String text = "This is a test";
            int width = fm.stringWidth(text);
            int height = fm.getHeight();
            imgTet = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = imgTet.createGraphics();
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, 0, fm.getAscent());
            g2d.dispose();
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(imgTet, 0, 0, getWidth(), imgTet.getHeight(), this);
            g2d.dispose();
        }

    }

}