我正在尝试使用 html 作为文本将 JLabel 绘制到 BufferedImage,但它总是在中间(垂直)打印文本,并切断右侧的文本。
这是我的代码:
public static void test() throws IOException
{
int width = 100;
JLabel label = new JLabel();
label.setText("<html><body><p>asdf asdfasdf asdfsdf asdfasdf asdfasdf asdfasdfasdfasdf asdfasdfasdfa sdfasd fasdf asdfasdf asdfasdf asdfasdfasdfa sdfasdf</p></body></html>");
Dimension size = getPreferredSize(label.getText(), true, width);
label.setSize(size);
BufferedImage image =
new BufferedImage(
label.getWidth(),
label.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, 500, 900);
label.paint(g);
ImageIO.write(image, "png", new File("testImage.png"));
}
private static final JLabel resizer = new JLabel();
public static java.awt.Dimension getPreferredSize(
String html,
boolean width,
int prefSize)
{
resizer.setText(html);
View view =
(View) resizer
.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);
view.setSize(width ? prefSize : 0, width ? 0 : prefSize);
float w = view.getPreferredSpan(View.X_AXIS);
float h = view.getPreferredSpan(View.Y_AXIS);
return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));
}
这是生成的图像: