我正在做一个大学项目,但是很难将组件与电路板网格对齐。电路板将始终保持1:1的宽高比,但尺寸可能会有所不同。这是我尝试过的结果:
为什么对于1200x1200的实际图像尺寸,这些百分比与我计算的百分比不一致?
这是我的布局代码:
public class BoardPanel extends ViewComponent {
public static final int ROWS = 27;
public static final int COLS = 23;
private Board board = new Board();
private BufferedImage background = ResourceLoader.openImage("images/board.jpg");
public BoardPanel() {
this.add(board, "pos 4.5% 4.5%, width 76.5%, height 91%");
}
@Override
public void paintContent(Graphics2D g) {
g.drawImage(background, 0, 0, getHeight(), getHeight(), null);
}
private class Board extends ViewComponent {
public Board() {
setLayout(new GridLayout(ROWS, COLS, 1, 1));
for (int row = 0; row < ROWS; row++)
for (int col = 0; col < COLS; col++)
this.add(new Location(row, col));
}
}
}
最佳答案
作为替代方案,使用BufferedImage#getSubimage()
将图像分成多个一致的部分,如here所示。