2010-10-12 134 views
7

我想在bufferedimage上繪製水平線和垂直線。它最終應該看起來像一個網格單元格。但是當我運行代碼時,我只看到兩行:最左邊的行和最上面的行(即從0,0到0的一行,圖像的高度&,0,0到圖像的寬度,0)這裏是代碼片段:在BufferedImage中繪製多條線

BufferedImage mazeImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB); 
    Graphics2D g2d = mazeImage.createGraphics(); 
    g2d.setBackground(Color.WHITE); 
    g2d.fillRect(0, 0, imgDim.width, imgDim.height); 
    g2d.setColor(Color.BLACK); 
    BasicStroke bs = new BasicStroke(2); 
    g2d.setStroke(bs); 
    // draw the black vertical and horizontal lines 
    for(int i=0;i<21;i++){ 
    g2d.drawLine((imgDim.width+2)*i, 0, (imgDim.width+2)*i, imgDim.height-1); 
    g2d.drawLine(0, (imgDim.height+2)*i, imgDim.width-1, (imgDim.height+2)*i); 
    } 

而被覆蓋的paint方法:

public void paint(Graphics g) { 
    g.drawImage(mazeImage, 0, 0, this); 
} 

這一切都是在一個名爲RobotMaze類擴展JPanel。任何幫助表示讚賞。

回答

8
import java.awt.*; 
import java.awt.image.*; 
import javax.swing.*; 

class GridLines { 

    public static void main(String[] args) { 

     Dimension imgDim = new Dimension(200,200); 
     BufferedImage mazeImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB); 


     Graphics2D g2d = mazeImage.createGraphics(); 
     g2d.setBackground(Color.WHITE); 
     g2d.fillRect(0, 0, imgDim.width, imgDim.height); 
     g2d.setColor(Color.BLACK); 
     BasicStroke bs = new BasicStroke(2); 
     g2d.setStroke(bs); 
     // draw the black vertical and horizontal lines 
     for(int i=0;i<21;i++){ 
      // unless divided by some factor, these lines were being 
      // drawn outside the bound of the image.. 
      g2d.drawLine((imgDim.width+2)/20*i, 0, (imgDim.width+2)/20*i,imgDim.height-1); 
      g2d.drawLine(0, (imgDim.height+2)/20*i, imgDim.width-1, (imgDim.height+2)/20*i); 
     } 

     ImageIcon ii = new ImageIcon(mazeImage); 
     JOptionPane.showMessageDialog(null, ii); 
    } 
} 
+0

該死啊我!本來應該使用每個單元格變量的大小而不是整個維度......對於這個蹩腳的問題傢伙抱歉抱歉,指出這一點。 – Adith 2010-10-12 12:35:01

0

如果i> 0,您如何預期(imgDim.width+2)*i的結果在圖像邊界內?

+0

是的我認識到,現在... :( – Adith 2010-10-12 12:38:34

1

打印出你的座標,你會看到你的圖像的寬度和高度的外部繪製點:

System.out.printf("Vertical: (%d,%d)->(%d,%d)\n",(imgDim.width+2)*i, 0, (imgDim.width+2)*i, imgDim.height-1); 
System.out.printf("Horizontal: (%d,%d)->(%d,%d)\n",0, (imgDim.height+2)*i, imgDim.width-1, (imgDim.height+2)*i);