【问题标题】:Drawing multiple lines in a BufferedImage在 BufferedImage 中绘制多条线
【发布时间】:2015-08-26 22:47:51
【问题描述】:

我正在尝试在缓冲图像上绘制水平线和垂直线。它最终应该看起来像一个单元格网格。但是当我运行代码时,我只看到两行:最左边的行和最上面的行(即从 0,0 到 0 的行,图像的高度和 0,0 到图像的宽度,0) 这是代码 sn -p:

  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。任何帮助表示赞赏。

【问题讨论】:

    标签: java swing drawing lines bufferedimage


    【解决方案1】:
    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);
        }
    }
    

    【讨论】:

    • 啊该死!我应该使用每个单元格变量的大小而不是整个维度...抱歉,伙计们提出了蹩脚的问题,感谢您指出这一点。
    【解决方案2】:

    打印出你的坐标,你会看到你在图像的宽度和高度之外绘制点:

    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);
    

    【讨论】:

      【解决方案3】:

      如果 i > 0,您如何期望 (imgDim.width+2)*i 的结果在图像边界内?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        相关资源
        最近更新 更多