0

我正在尝试使用 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));
}

这是生成的图像:

在此处输入图像描述

4

1 回答 1

-1

我认为 html 自动换行是由 swing 线程循环中的某些东西处理的,如果你正在执行这种循环作为 actionlistener 的表单,那么它就无法重新计算 html

于 2017-08-04T15:55:29.657 回答