如何根据文本大小自动换行
g.drawString("Hello, please help me in wrapping the text", 100, 100);
输出 - 直线文本:
所需输出 - 根据文本长度换行文本:
如何实现所需的输出?浪费了很多时间来计算它,但没有用,非常感谢解释。
最佳答案
使用 HTML 换行是解决此问题的最简单方法。
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String title = "<html><body style='"
+ "text-align: center; width: 100px; padding: 5px;'>"
+ "<p>Hello, please help me in<br>wrapping the text";
BufferedImage image = new BufferedImage(
200,
100,
BufferedImage.TYPE_INT_RGB);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
textLabel.setForeground(Color.WHITE);
Graphics2D g = image.createGraphics();
textLabel.paint(g);
g.dispose();
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));
}
});
}
}
关于java - 使用图形在图像上进行文本换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43085766/