我想在不显示JLabel的情况下生成与JLabel标签相同的文本图像。如何生成与JLabel标签相同的文本图像?
我试过相同的字体,相同的绘图方法。
但生成的图像与JLabel不同。
我的源代码如下。
*'super.paintComponent(g)'已被注释掉,为清楚起见,它是相同的方式。输出图像相同。
*下图'View.paint'方法,但我也试过'SwingUtilities2.drawString'。两个结果是一样的。
/* Label */
JLabel label = new JLabel(text) {
@Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
View v = BasicHTML.createHTMLView(this, getText());
v.paint(g, new Rectangle(0, 0, getWidth(), getFontMetrics(
getFont()).getAscent()));
}
};
label.setFont(new Font("Consolas", Font.PLAIN, 13));
/* Image */
FontMetrics fm = label.getFontMetrics(font);
BufferedImage image = new BufferedImage(fm.stringWidth(text),
fm.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setFont(label.getFont());
// Clear background.
g2d.setPaint(label.getBackground());
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
// Draw string.
g2d.setClip(new Rectangle(0, 0, image.getWidth(), image.getHeight()));
View v = BasicHTML.createHTMLView(label, text);
v.paint(g2d, new Rectangle(0, 0, image.getWidth(),
g2d.getFontMetrics().getAscent()));
// ... output image to file ...
结果图像如下。
[JLabel的]
[生成的图像]
生成的图像稍薄面,相比于JLabel的捕获。
如何生成与JLabel标签相同的文本图像?
谢谢您的考虑。
我的rendering quality支付左右我不确定,但在这里需要查看吗?通过调用label.paint(g2b)不可能直接在Graphics2D上渲染标签? –
这很容易,但结果是一样的。谢谢你的建议。 – Msyk