6

I know how to get a BufferedImage from JComponent, but how to get a BufferedImage from a Component in java ? The emphasis here is an object of the "Component" type rather than JComponent.

I tried the following method, but it return an all black image, what's wrong with it ?

  public static BufferedImage Get_Component_Image(Component myComponent,Rectangle region) throws IOException
  {
    BufferedImage img = new BufferedImage(myComponent.getWidth(), myComponent.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = img.getGraphics();
    myComponent.paint(g);
    g.dispose();
    return img;
  }
4

2 回答 2

8

Component有方法paint(Graphics)。该方法将在传递的图形上绘制自己。这就是我们要用来创建的BufferedImage,因为 BufferedImage 有方便的方法getGraphics()。这将返回一个Graphics-object,您可以使用它在BufferedImage.

更新:但我们必须预先配置绘图方法的图形。这就是我在java.sun.com上发现的关于 AWT 组件渲染的内容:

当 AWT 调用此方法时,Graphics 对象参数会预先配置适当的状态以在此特定组件上绘图:

  • Graphics 对象的颜色设置为组件的前景属性。
  • Graphics 对象的字体设置为组件的字体属性。
  • Graphics 对象的平移设置为坐标 (0,0) 表示组件的左上角。
  • Graphics 对象的剪辑矩形设置为需要重新绘制的组件区域。

所以,这是我们得到的方法:

public static BufferedImage componentToImage(Component component, Rectangle region) throws IOException
{
    BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics g = img.getGraphics();
    g.setColor(component.getForeground());
    g.setFont(component.getFont());
    component.paintAll(g);
    if (region == null)
    {
        region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
    }
    return img.getSubimage(region.x, region.y, region.width, region.height);
}
于 2010-10-04T18:12:26.843 回答
1

你可以尝试使用Component.paintAll.

您还可以将对 Graphics 对象(来自缓冲图像)的引用传递给SwingUtilities.paintComponent.

于 2010-10-04T18:07:29.973 回答