如何将每个paintComponent调用同时写入BufferedImage?

时间:2014-08-08 13:02:52

标签: java swing awt bufferedimage paintcomponent

如何通过JPanel类型(即extends /从JPanel继承的自定义类)将每个重绘调用(直接或非直接)写入{{1 }

在自定义类中做这种事情' BufferedImage不起作用:

paintComponent

结果protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D G2 = (Graphics2D) g; // ... draw objects BufferedImage imageBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); G2 = imageBuffer.createGraphics(); // Which doesn't work, because with that method it seems you would // need to call paint() on Graphics2D reference here. // And to do so would then throw an Illegal Exception. } 是调用BufferedImage的{​​{1}}类型类的正确大小,但是图像是黑色的(即空的) - 这完全是逻辑的,因为{{1}单独不做任何事。

我知道Rob Camick的ScreenImage代码 - 但这似乎只适用于程序初始化时的单个屏幕截图。

让我感到困惑的是,JPanel在显示在屏幕上之前必须保留在内存中...所以有没有办法每次都抓住它并将其保存到paintComponent

3 个答案:

答案 0 :(得分:1)

这种方法怎么样?与您发布的代码的不同之处在于,您需要在BufferedImage上完成所有自定义绘图。然后你只在组件上绘制一个东西:BufferedImage

public void paintComponent(Graphics g) {
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g;

    BufferedImage imageBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics imageG2 = imageBuffer.createGraphics();

    // do custom painting onto imageG2...

    // save imageBuffer

    g2.drawImage(imageBuffer, 0, 0, this);  // draw onto component
}

答案 1 :(得分:1)

描述和一些细节可能不完全清楚。但它基本上听起来像是要创建一个可以像普通JPanel一样使用的组件,但paintComponent方法中绘制的所有内容也应保存为BufferedImage。< / p>

对此有不同的解决方案。您可以拨打专用电话,例如

myComponent.paintComponent(bufferedImageGraphics);

并相应地处理图像,如一个答案中所提出的。另一个答案建议创建一个自定义paintComponent方法来执行图像处理。

但是,我想提出以下解决方案:您可以创建一个扩展ImageSavingComponent的{​​{1}}类。在本课程中,您不能覆盖JPanel方法,而是覆盖paintComponent方法。 paint方法做了两件事:

  • 调用paint,绘制成图像
  • 调用super.paint(bufferedImageGraphics),画在屏幕上

这样,您可以简单地扩展此类,并像对待任何super.paint(componentGraphics)一样实施paintComponent方法。图像处理可以完全透明地完成。

在下面的示例中,我添加了一个JPanel接口,用于接收图像并对其进行适当处理。如果ConsumerConsumer,则不会生成任何图片。为了测试,我创建了一个这个接口的实现,它只是每200ms将图像存储在文件中。 (如果需要,可以用Java 8 null接口替换此接口)

Consumer

答案 2 :(得分:0)

您必须在组件的paint函数之外创建BufferedImage,然后使用BufferedImage图形作为参数调用此paint函数。

BufferedImage imageBuffer = new BufferedImage(comp.getWidth(), cmp.getHeight(), BufferedImage.TYPE_INT_RGB);
cmp.paint(imageBuffer.getGraphics());