在BufferedImage中绘制多条线
我试图在bufferedimage上绘制水平和垂直线。它最终应该看起来像一个网格单元。但是,当我运行代码时,我只看到两行:最左边的行和最上面的行(即,从0,0到0,图像的高度和从0,0到图像的宽度,0的一行),这里是代码段:
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);
}
和覆盖的绘制方法:
public void paint(Graphics g) { g.drawImage(mazeImage, 0, 0, this);
}
所有这些都在扩展了JPanel的名为RobotMaze的类中。任何帮助表示赞赏。
回答:
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);
}
}
以上是 在BufferedImage中绘制多条线 的全部内容, 来源链接: utcz.com/qa/403958.html