I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working).

I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results.

My assumption is the following:

Assuming I am using i to specify rows and j to specify columns that any given pixel in a 2D texture can be calculated by the sum of i * j or is this incorrect?

  • \$\begingroup\$ Try i*width + j \$\endgroup\$ – Nathan Reed Aug 28 '14 at 7:00
  • \$\begingroup\$ Im not an xna developer, but does GetData return an array of 'pixels' or an array of bytes? \$\endgroup\$ – RamblingMad Aug 28 '14 at 9:39
  • \$\begingroup\$ Its a generic, so it returns an array of objects of the specified type. msdn.microsoft.com/en-us/library/bb197089.aspx \$\endgroup\$ – Seta Aug 28 '14 at 10:30

The answer to this question here should help explain how to use the GetData function.

Basically, the data is stored in the return array from the GetData call is formed by reading the 2D texture from left to right, top to bottom, transforming it as follows:


To determine where a given pixel in the 1D array is, we use the index calculation of i + (j * width) should return the correct pixel at any given point.

Your assumptions is almost correct, you are just forgetting to take the width into account. Basically, multiply the Y coord (your j value) by the width of the Texture to select the correct start of the index block containing your pixel, then add the X coord (your i value) to select the correct pixel from that block.

In the sample above, assuming we want the value at (1,2), we have the following equation.

v = i + (j * width)
v = 1 + (2 * 4)
v = 1 + 8
v = 9
item at offset 9 = C

On 2nd though, that first link probably isn't the best, its just the first one I found with the required math. Here's another one that describes (sortof) how to use it.

  • \$\begingroup\$ So are you saying the X position is the row of the pixel (in the texture itself) and (Y * width) is the Y co-ordinate of the pixel in the 2D Texture? \$\endgroup\$ – Scott Aug 28 '14 at 8:16
  • \$\begingroup\$ I've updated my answer, hopefully it clears things up a bit. \$\endgroup\$ – Seta Aug 28 '14 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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