1
\$\begingroup\$

I am attempting to retrieve the color data for a given sprite located on a texture atlas by creating a new color and passing a source rectangle width and height for the given sprite. I am then passing this color variable into XNA's Texture.GetData method, as seen below. When this code is executed at runtime I receive the following message "Size of the data passed in is too large or too small for this resource."

Texture2D texture = level.Tiles[x, y].Texture;
Rectangle source = level.Tiles[x, y].Source;

Color[] colorData = new Color[source.Width * source.Height];
texture.GetData(colorData);

As far as I am aware this approach should work as it has worked previously with other spritesheets within the application. Could someone please explain why such a message would be thrown in the first place and how I may resolve it?

\$\endgroup\$
1
\$\begingroup\$

It seems I have managed to resolve the issue by using the overloaded Texture2D.GetData (int level, Rectangle? rect, T[] data, int startIndex, int elementCount) method.

Texture2D texture = level.Tiles[x, y].Texture;
Rectangle source = level.Tiles[x, y].Source;

Color[] colorData = new Color[source.Width * source.Height];
texture.GetData(0, source, colorData, 0, colorData.Length);

However I am still unaware as to why I recieved the error message in the first place. Any information on this would be appreciated.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ You're probably not computing the size of the buffer properly (not accounting for stride, varying bit-depth, or something like that). The first attempt throws because the buffer you pass doesn't exactly match the size of the data. The second call works because you explicitly pass the length of the buffer for the argument that says "get only this many elements," which will work as long as the actual resource is at least many bytes in size. \$\endgroup\$ – user1430 Oct 10 '14 at 16:44
  • 1
    \$\begingroup\$ It looks like your first case was attempting to get the whole texture, rather than was just the tile. Since your color array was the size of a tile, not of the texture, it was an invalid array. In the second case, you're telling it which rectangle/tile to pull, so the array is the correct size for that part of the image. \$\endgroup\$ – Shane S. Anderson Oct 10 '14 at 17:48
  • \$\begingroup\$ Thanks for the information. I'll bear that in mind next time. \$\endgroup\$ – Nexuz Oct 12 '14 at 14:37

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.