2009-06-16 58 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; 
} 
相关问题