我正在创建一个带有许多独立小方块的电路板,我想用图像的各个部分填充方块,这样它们就可以一起形成原始图像。我怎么做?我应该研究什么课?顺便说一句,我正在使用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 :(得分: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);