2013-07-30 44 views
0

我想使它在圖像中的像素位置(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); 
} 

}

enter image description here

+0

嗯......什麼問題 – aaronman

+0

i * j是可交換的,所以你需要像我這樣的*常量+ j – BevynQ

回答

0

在雙迴路檢查i = j時然後跳過有效負載。

0

明知i=0, j=999是第1000個像素,而i=999, j=0是999001th像素,你怎麼能夠讓像素映射f(i,j) != f(j,i)以顏色不先存儲在列表中的顏色?

pixel = i * 1000 + j + 1; 

至於它們存儲在一個列表而言,這可能是你最好的方法,因爲預先計算往往使事情更快。雖然我可能會做一個二維數組。喜歡:

private void getAllColors() { 
    colors = new Color[1000][1000]; 
    int i = 0; int j = 0; 
    loop: 
    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[i++][j] = new Color(R, G, B)); 
       if (i == 1000) { 
        j++; 
        i = 0; 
        if (j == 1000) break loop; 
       } 
      } 
     } 
    } 
} 
相關問題