【发布时间】:2013-02-03 08:40:54
【问题描述】:
是否可以水平拉伸java中的文本。我知道它应该在那里,但我无法弄清楚。字体大小影响文本的高度和宽度。我尝试使用 FontMetrics,但它只给了我文本的宽度。但我只需要更改文本宽度,使其看起来好像被拉伸了。
如果有人知道这样做,请告诉我。 提前致谢。
【问题讨论】:
-
@stacker 不错,我喜欢这个链接!
是否可以水平拉伸java中的文本。我知道它应该在那里,但我无法弄清楚。字体大小影响文本的高度和宽度。我尝试使用 FontMetrics,但它只给了我文本的宽度。但我只需要更改文本宽度,使其看起来好像被拉伸了。
如果有人知道这样做,请告诉我。 提前致谢。
【问题讨论】:
可能还有其他方法可以实现相同的结果,例如将文本转换为形状并使用AffineTransformation,但这是手头的...
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();
}
}
}
【讨论】:
KEY_TEXT_ANTIALIASING?!?天哪,这世界怎么了?下一个孩子会不尊重他们的父母,社会就会崩溃。请参阅this answer 以恢复所有“好和好”的东西。 +1(什么......你认为我在咆哮时不是认真的,......是吗?)