我想在不顯示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