以下示例是在C#中从XNA中的Texture2D中提取数据。我的理解是,Texture2D.GetData最初不能用于将数据拉入2D数组。
如果1D数组包含如下值:1, 2, 3, 4, 5, 6, 7, 8, 9
是否可以将该单维数组复制到2D数组中,其中2D数组的值如下:
1, 2, 3
4, 5, 6
7, 8, 9
我的目标是将整个数组从1D复制到2D,而不是迭代并计算索引。我目前的代码是这样的:
Color[,] TextureDataTo2DArray(Texture2D texture)
{
Color[] colors1D = new Color[texture.Width * texture.Height];
texture.GetData(colors1D);
Color[,] colors2D = new Color[texture.Width, texture.Height];
for (int x = 0; x < texture.Width; x++)
for (int y = 0; y < texture.Height; y++)
colors2D[x, y] = colors1D[x + y * texture.Width];
return colors2D;
}
答案 0 :(得分:1)
在将一维数组复制到二维数组中时,模数运算是你的朋友:
Color[,] TextureDataTo2DArray(Texture2D texture)
{
Color[] colors1D = new Color[texture.Width * texture.Height];
texture.GetData(colors1D);
Color[,] colors2D = new Color[texture.Width, texture.Height];
for (int i = 0; i < colors1D.Length; i++)
colors2D[Math.Floor(i / texture.Width), i % texture.Width] = colors1D[i];
return colors2D;
}
但是,最终,如果你正在重塑一个数组,你将不得不计算一个形状与另一个形状之间的对应关系。
答案 1 :(得分:0)
你可以增加一个计数器
index = 0;
for (int x = 0; x < texture.Width; x++)
for (int y = 0; y < texture.Height; y++)
colors2D[x, y] = colors1D[index++];
答案 2 :(得分:0)
static void Main(string[] args)
{
int Size_of_OneDimensional = 0;
int Start_Index = 0;
int row = 0;
int column=0;
Console.WriteLine("Enter The number of elements you want to add in 1-D Array : ");
Size_of_OneDimensional = Convert.ToInt32(Console.ReadLine());
int[] One_Dimensional = new int[Size_of_OneDimensional];
for (int i = 0; i < Size_of_OneDimensional; i++)
{
Console.WriteLine("Enter "+i+" Element");
One_Dimensional[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Emter Number of Row : ");
row = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Emter Number of Colum : ");
column= Convert.ToInt32(Console.ReadLine());
int[,] Two_Dimensional = new int[row, column];
Console.WriteLine("Here is your 2-D Array");
for (int i = 0; i < row; i++)
{
if (Start_Index == One_Dimensional.Length)
break;
for(int j = 0; j < column; j++)
{
Two_Dimensional[i, j] = One_Dimensional[Start_Index];
Start_Index++;
Console.Write(Two_Dimensional[i, j]);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}