Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

This is question has been really killing me. In XNA when you want to convert an image to color data using Texture.GetData, it only lets you make it a one dimensional array instead of a 2D one. This makes it much more difficult to work with. Is there a specific reason it's like that?

share|improve this question
    
I could only guess that it has something to do with performance when drawing, transforming or manipulating the Texture. Maybe a those actions can be carried out more efficiently in a one dimensional array than a two dimensional one? –  Christian Jan 4 '13 at 14:07

2 Answers 2

up vote 9 down vote accepted

Xna is built uppon Directx and Directx use this strategy cause this is how the the display driver exposes information it gets from the video board. (actually it exposes an array of bytes). Also to give you a 2d array, the api would need to know the "size" of each texel and the dimensions of you texture to make the conversion. For performance reason, they let the user decide if they want/need to make the conversion.

You can always convert the recovered array in a 2d one. (or you can wrap it in a class that make the coordinate conversion)

share|improve this answer
    
Oh ok, thanks for the help. I'm probably just going to write an extension to do the 2D conversion. –  redcodefinal Jan 4 '13 at 18:19

As Tpastor had a great answer on why, here is how to convert it from the hard to read 1D array, to a simple 2D array for easy access to each pixel.

Color[,] TextureTo2DArray(Texture2D texture)
    {
        Color[] colorsOne = new Color[texture.Width * texture.Height]; //The hard to read,1D array
        texture.GetData(colorsOne); //Get the colors and add them to the array

        Color[,] colorsTwo = new Color[texture.Width, texture.Height]; //The new, easy to read 2D array
        for (int x = 0; x < texture.Width; x++) //Convert!
            for (int y = 0; y < texture.Height; y++)
                colorsTwo[x, y] = colorsOne[x + y * texture.Width];

        return colorsTwo; //Done!
    }
share|improve this answer
    
Thanks, I already implemented it but, I'm sure other similarly confused people will find it useful. :) –  redcodefinal Jan 5 '13 at 18:28
2  
Oh, also, you should change the parameter to (this Texture2D texture) so it extends Texture2D to have that method. –  redcodefinal Jan 5 '13 at 18:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.