2009-06-16 62 views
0

我下面的代碼給了我錯誤:「索引超出了數組的範圍。」我的算法創建的顏色數組的數組維度'16', 但我需要第二個'colorSetLegend'尺寸:32如果你看下面的粗體代碼,返回我的錯誤。如何將顏色數組設置爲另一個顏色數組?

Color[] colorSetLegend = new Color[32]; 
      Color[] colorSet = { Color.Red, Color.Blue, Color.Green, Color.Yellow }; 
      Color end = Color.White; 
      colorSet = ColorMaker.GenerateColor(colorSet, end); 

      for (int i = 0; i < colorSet.Length;) 
      { 
       for (int j = 0; j < colorSetLegend.Length;) 
       { 
        colorSetLegend[j] = colorSet[i]; 
        colorSetLegend[j++] = Color.Black; 
        i++; 
       } 
      }

我的色彩以下發電機:


public class ColorMaker 
{ 
    public static Color[] GenerateColor(Color[] baseColorSet, Color end) 
    { 
     Color[] colorSet = new Color[16]; 
     int j = 0; 
     foreach (Color start in baseColorSet) 
     { 
      for (int i = 0; i < 15; i += 4) 
      { 
       int r = Interpolate(start.R, end.R, 15, i), 
        g = Interpolate(start.G, end.G, 15, i), 
        b = Interpolate(start.B, end.B, 15, i); 

       colorSet[j] = Color.FromArgb(r, g, b); 
       j++; 
      } 
     } 

     return colorSet; 

    } 
    static int Interpolate(int start, int end, int steps, int count) 
    { 
     float s = start, e = end, final = s + (((e - s)/steps) * count); 
     return (int)final; 
    } 
} 

回答

2

你增加我在你循環。我懷疑你的意圖是在外層循環中這樣做 - 否則在一個迭代你的外層循環時,你會多次增加i,直到你超出數組邊界。

或者,你可以寫你的for循環一樣人人方式都這麼做:

for (int i = 0; i < colorSet.Length; i++) 
{ 
    for (int j = 0; j < colorSetLegend.Length; j++) 
    { 
     colorSetLegend[j] = colorSet[i]; 
     colorSetLegend[j] = Color.Black; 
    } 
} 

說了這麼多,該代碼是一個有點無意義鑑於循環內的第一行設置colorSetLegend[j]和第二線套同樣的元素再次。此外,在外循環的下一次迭代中,您將再次覆蓋colorSetLegend中的所有值。你想達到什麼目的?

馬克在你的目標做了一個好看的猜測在這裏(雖然他現在刪除了他的答案!)

這是他的工作代碼猜測你想要的東西:

for (int i = 0; i < colorSet.Length; i++) 
{ 
    colorSetLegend[i*2] = colorSet[i]; 
    colorSetLegend[(i*2)+1] = Color.Black; 
} 

幾件事從中學習,如果他是對的:

  • 想想你的循環嵌套的級別。你真的有意在這裏有兩個循環嗎?
  • 嘗試使用傳統的常用成語循環 - 每當我看到一個空位在for循環的開始結束,我會緊張
  • 另一種表達是使用前和後遞增運營商是容易出錯。
+0

ForExample; colorSetLegend [0] =「紅色」; colorSetLegend [1] = Color.Black; colorSetLegend [2] =「FireBrick」; colorSetLegend [3] = Color.Black; – Penguen 2009-06-16 13:49:42

+0

聽起來像馬克的猜測是正確的。看看我編輯的答案。 – 2009-06-16 13:52:07

0

這將實現你在找什麼:

int j = 0; 
for (int i = 0; i < colorSet.Length; i++) 
{ 
    colorSetLegend[j++] = colorSet[i]; 
    colorSetLegend[j++] = Color.Black; 
} 
相關問題