【发布时间】:2012-09-25 10:37:56
【问题描述】:
我想生成与 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 标签相同的文本图像?
谢谢您的考虑。
【问题讨论】:
-
我不确定,但是这里需要查看吗?是不是可以通过调用 label.paint(g2b) 直接在 Graphics2D 上渲染标签?
-
这很容易,但结果是一样的。感谢您的建议。