2012-11-26 83 views
0

我想繪製2個圖像,一個在另一個之上。第1個圖像是一個箭頭(在最終圖像中應該顯示爲標題)。第一個圖像(箭頭)是32x32像素,而第二個圖像是24x24像素。繪製兩個覆蓋圖像

理想情況下,我想從第1個圖像的右下角開始在第1個頂部繪製第2個圖像。

目前我使用這樣的代碼

// load source images 
     BufferedImage baseImage = ImageIO.read(new File(baseImg.getFileLocation())); 
     BufferedImage backgroundImage = ImageIO.read(new File(backgroundImg.getFileLocation())); 

     // create the new image, canvas size is the max. of both image sizes 
     int w = Math.max(baseImage.getWidth(), backgroundImage.getWidth()); 
     int h = Math.max(baseImage.getHeight(), backgroundImage.getHeight()); 
     BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); 

     // paint both images, preserving the alpha channels 
     Graphics g = combined.getGraphics(); 
     g.drawImage(baseImage, 0, 0, null); 
     g.drawImage(backgroundImage, 0, 0, null); 

     int index = baseImg.getFileLocation().lastIndexOf(".png"); 
     String newFileName = baseImg.getFileLocation().substring(0, index); 
     // Save as new image 
     ImageIO.write(combined, "PNG", new File(newFileName + "_combined.png")); 

但是這對我來說不是很的工作,因爲最終的結果是與第二圖象只被繪製的32×32的圖像。

任何幫助表示讚賞。

謝謝!

回答

1

看起來問題在於你最後繪製的是32x32背景圖像,這意味着它將被打印在另一幅圖像的頂部,使得它看起來好像24x24圖像從未被繪製過。

如果將這兩行交換,應該會看到兩個圖像。來源:

g.drawImage(baseImage, 0, 0, null); 
g.drawImage(backgroundImage, 0, 0, null); 

到:

g.drawImage(backgroundImage, 0, 0, null); 
g.drawImage(baseImage, 0, 0, null); 


然而,這將以此爲24x24的圖像中的左上角,你說你想它在右下角。這可以通過一些基本的減法來完成:

g.drawImage(baseImage, w - baseImage.getWidth(), h - baseImage.getHeight(), null);