【问题标题】:How can I generate text image same as the JLabel label?如何生成与 JLabel 标签相同的文本图像?
【发布时间】: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 上渲染标签?
  • 这很容易,但结果是一样的。感谢您的建议。

标签: java swing graphics


【解决方案1】:

我不确定,但您可能需要创建兼容的缓冲图像(与显示器兼容)

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();

// Create an image that does not support transparency
BufferedImage bimage = gc.createCompatibleImage(100, 100, Transparency.OPAQUE);

这至少会让您了解用于渲染到屏幕的图形

您可能还想使用rendering quality 付款

Kleopatra 不久前就类似的问题发表过一篇文章,您可能会尝试追捕它

【讨论】:

  • 感谢您的建议。我会搜索类似的问题并尝试任何想法。
  • 我通过 RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB 解决了我的问题。谢谢!
  • 我会在几个系统上测试它,看看它在不同的显示器上看起来是否有任何不同。但否则王牌!
【解决方案2】:
  • 如果你想和JLabel一样,为什么要使用BasicHTML.createView
  • 您可以直接使用JLabel(如果您只想要文本而不想要背景,请将opaque 设置为false,将border 设置为null
  • 或者你可以使用g2d.drawString()

【讨论】:

  • 我正在创建软件,即从网络浏览器捕获图像中搜索文本位置。我想尝试通过生成相同的文本图像来搜索捕获图像。 JLabel 显示的文本与浏览器文本相同。因此我没有使用'g2d.drawString'。我想生成 JLabel 的文字图片。
猜你喜欢
  • 2018-07-25
  • 1970-01-01
  • 2016-11-06
  • 2013-10-12
  • 2017-10-24
  • 2018-01-05
  • 2017-01-14
  • 2017-11-10
  • 1970-01-01
相关资源
最近更新 更多