我想使它在圖像中的像素位置(int i,int j)決定了該像素的顏色。這是爲了在java2d遊戲中的爆炸效果,我希望通過使爆炸的顏色取決於爆炸的位置來變得更加酷。我目前所做的是創建顏色ArrayList
,然後使用i*j
作爲索引,在1000x1000圖像上測試此圖顯示沿着對角線的鏡像,這自然是因爲i*j = j*i
圍繞對角線顯示,如下所示。如何將像素位置i,j映射到顏色?
知道i=0, j=999
是第1000個像素,而i=999, j=0
是999001th像素如果沒有首先將顏色存儲在列表中,您如何獲得像素到顏色的映射f(i,j) != f(j,i)
?顏色排序非常重要,也就是說顏色是使用R,0,0
然後0,G,0
然後0,0,B
構建的,顯然問題並不清楚。 注意getAllColors
,它會按順序創建顏色並將它們添加到列表中,注意g2d.setColor(i*j)
,它會按順序設置顏色,除非它沿着對角線反射。我想知道是否可以將顏色映射到索引(按順序),而不將其存儲在列表中,同時避免沿着對角線進行鏡像。
全MCVE
public class AllColors extends JPanel {
private int width, height;
private double colorIncrement;
private List<Color> colors;
public AllColors(int width, int height) {
this.width = width;
this.height = height;
this.colorIncrement = 1.0/Math.pow(1.0 * width * height, 1.0/3);
this.colors = new ArrayList<>(width * height);
getAllColors();
}
@Override
@Transient
public Color getBackground() {
return Color.black;
}
@Override
@Transient
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// Notice i*j= j*i around diagonal, the problem
g2d.setColor(colors.get(i * j));
g2d.fillRect(i, j, 1, 1);
}
}
}
private void getAllColors() {
for (float R = 0; R < 1.0; R += colorIncrement)
for (float G = 0; G < 1.0; G += colorIncrement)
for (float B = 0; B < 1.0; B += colorIncrement)
colors.add(new Color(R, G, B));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
AllColors allColors = new AllColors(800, 800);
frame.getContentPane().add(allColors);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
嗯......什麼問題 – aaronman
i * j是可交換的,所以你需要像我這樣的*常量+ j – BevynQ