gpt4 book ai didi

java - 在 BufferedImage 中绘制多条线

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:01 24 4
gpt4 key购买 nike

我正在尝试在缓冲图像上绘制水平线和垂直线。它最终应该看起来像一个单元格网格。但是当我运行代码时,我只看到两行:最左边的行和最上面的行(即从 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);
}

这一切都在一个名为 RobotMaze 的类中,该类扩展了 JPanel。感谢您的帮助。

最佳答案

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

关于java - 在 BufferedImage 中绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3914265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com