是否可以按照说明将1D阵列复制到2D阵列,如果可以,如何进行? [英] Is it possible to copy a 1D array to a 2D array as described and if so, how?

查看:59
本文介绍了是否可以按照说明将1D阵列复制到2D阵列,如果可以,如何进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的示例在C#中从XNA的Texture2D中提取数据.我的理解是Texture2D.GetData最初不能用于将数据拉入2D数组.

The example below is in C# pulling data from Texture2D in XNA. My understanding is that Texture2D.GetData can not be used to pull data into a 2D array initially.

如果一维数组包含以下值: 1、2、3、4、5、6、7、8、9

If a 1D array contains values like so: 1, 2, 3, 4, 5, 6, 7, 8, 9

是否可以将一维数组复制到2D数组中,然后2D数组具有如下值:

Is it possible to copy that single dimensional array into a 2D array where the 2D array then has the values like so:

1, 2, 3
4, 5, 6
7, 8, 9

我的目标是将整个数组从1D复制到2D,而不是遍历和计算索引.我当前的代码是这样的:

My goal is to copy the whole array from 1D to 2D rather than iterating through and calculating indexes. My current code is like this:

    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;
    }

推荐答案

在将1D数组复制到2D数组中时,模块化算术是您的朋友:

In copying a 1D array into a 2D array, modular arithmetic is your friend:

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;
    }

最终,如果要重塑数组,则必须计算一种形状与另一种形状之间的对应关系.

Ultimately, though, if you're reshaping an array, you're going to have to calculate the correspondence between one shape and another.

这篇关于是否可以按照说明将1D阵列复制到2D阵列,如果可以,如何进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆