2010-11-22 10 views
6

Ho bisogno di disegnare il contenuto di un componente e tutti i suoi sottocomponenti in una bitmap. Il seguente codice funziona perfettamente se voglio disegnare l'intero componente:Componente Java Paint in bitmap

public void printComponent(Component c, String format, String filename) throws IOException { 
// Create a renderable image with the same width and height as the component 
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); 

    // Render the component and all its sub components 
    c.paintAll(image.getGraphics()); 

    // Render the component and ignoring its sub components 
    c.paint(image.getGraphics()); 
// Save the image out to file 
ImageIO.write(image, format, new File(filename)); 

}

ma non ho trovato un modo per disegnare solo una regione di questo componente . Qualche idea?

risposta

6

avete bisogno di tradurre in questo modo:

BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); 

Graphics g = image.getGraphics(); 
g.translate(-100, -100); 

c.paintComponent(g); 

g.dispose(); 

esempio completo con uscita:

Resulting image

public static void main(String args[]) throws Exception { 

    JFrame frame = new JFrame("Test"); 
    frame.add(new JTable(new DefaultTableModel() { 
     @Override 
     public int getColumnCount() { 
      return 10; 
     } 
     @Override 
     public int getRowCount() { 
      return 10; 
     } 
     @Override 
     public Object getValueAt(int row, int column) { 
      return row + " " + column; 
     } 
    })); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(400, 300); 
    frame.setVisible(true); 

    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); 
    Graphics g = image.getGraphics(); 
    g.translate(-100, -100); 

    frame.paintComponents(g); 

    g.dispose(); 

    ImageIO.write(image, "png", new File("frame.png")); 
} 
+0

Non disegnerà la regione del componente che inizia nel punto 0,0 nella bitmap! – Arutha

+0

Il clip che ho impostato era un esempio, è necessario impostare questa regione su qualcosa di utile per te. – dacwe

+0

Se voglio disegnare la regione partendo dal punto (100.100) e con un siez di 100 * 100, ho bisogno di creare una bitmap con una dimensione di 100 * 100 e quindi quali sono i parametri per il metodo setClip? – Arutha