6

JComponent から BufferedImage を取得する方法は知っていますが、Java の Component から BufferedImage を取得する方法は? ここで強調しているのは、JComponent ではなく "Component" タイプのオブジェクトです。

次の方法を試しましたが、真っ黒な画像が返されました。何が問題なのですか?

  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)ます。そのメソッドは、渡されたグラフィックに自分自身を描画します。BufferedImageBufferedImage には便利なメソッド があるため、これを使用して を作成しますgetGraphics()Graphicsこれは、上に描画するために使用できる -object を返しますBufferedImage

更新:ただし、ペイント メソッドのグラフィックを事前に構成する必要があります。それが、 java.sun.comでの AWT コンポーネントのレンダリングについて見つけたものです。

AWT がこのメソッドを呼び出すと、Graphics オブジェクト パラメーターは、この特定のコンポーネントで描画するための適切な状態で事前構成されます。

  • Graphics オブジェクトの色は、コンポーネントの foreground プロパティに設定されます。
  • Graphics オブジェクトのフォントは、コンポーネントの font プロパティに設定されます。
  • 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 に答える