2015-12-22 35 views
0

我正在用許多獨立的小方塊創建一個紙板,我想用圖像的各個部分填充正方形,以便它們一起形成原始圖像。我怎麼做?我應該看什麼課程?順便說一句,我用paintComponent繪製板子。用給定圖像座標的圖像的一部分填充矩形?

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    int boxHeight = boxHeight(); 
    int boxWidth = boxWidth(); 
    for (int row = 0; row < game.getRows(); row++) { 
     for (int col = 0; col < game.getCols(); col++) { 
      g.setColor(Color.lightGray); 
      g.drawRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight); 
//this is where I want to fill the rectangles 
      if (game.isAlive(row, col)) { 
       g.setColor(color); 
       g.fillRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight); 
      } 
     } 
    } 
} 
+0

你的意思是這樣[這](http://stackoverflow.com/questions/11819669/absolute-positioning -graphic-jpanel-inside-jframe-blocked-by-blank-sections/11820847#11820847)或[this](http://stackoverflow.com/questions/11819669/absolute-positioning-graphic-jpanel-inside-jframe-阻斷逐空白截面/ 11822601#11822601)?訣竅是將圖像(使用'BufferedImage#subImage')分割成更小的圖像並將它們存儲爲像List這樣的東西,這樣可以更容易地顯示和管理 – MadProgrammer

回答

0

假如你有一個BufferedImage B:

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    int boxHeight = boxHeight(); 
    int boxWidth = boxWidth(); 
    for (int row = 0; row < game.getRows(); row++) { 
     for (int col = 0; col < game.getCols(); col++) { 
      g.setColor(Color.lightGray); 
      g.drawRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight); 
//this is where I want to fill the rectangles 
      if (game.isAlive(row, col)) { 
       g.setColor(color); 
       g.drawImage(b.getSubimage(col * boxWidth, row * boxHeight, boxWidth, boxHeight), col * boxWidth, row * boxHeight, boxWidth, boxHeight, null); 
      } 
     } 
    } 

假設你的圖像的尺寸與盒相同。否則,你必須縮小或擴大圖像:

BufferedImage b2=new BufferedImage(game.getCols()*boxWidth, game.getRows()*boxHeight, BufferedImage.TYPE_INT_RGB); 
Graphics g=b2.getGraphics(); 
g.drawImage(b, 0, 0, b2.getWidth(), b2.getHeight(), null); 

,並在環

g.drawImage(b2.getSubimage(col * boxWidth, row * box, boxWidth, boxHeight), col * boxWidth, row * boxHeight, boxWidth, boxHeight, null);