Creating a texture from a texture.

Hi folks.

I need a way to create a 32x32 color Array (or texture) from part of a larger texture. I have found an example to do exactly this, but it’s quite old and gives me HRESULT errors from Sharp, so I think things might have changed since it was posted.

Could someone help with this?


You could use the Texture2D.GetData() overload that allows you to specify the rect to grab data from, then use that data in Texture2D.SetData() on the new texture.

What was the example you used and can you give more details on the errors?

`Texture2D originalTexture = Content.Load(“myTexture”);
Rectangle sourceRectangle = new Rectangle(10, 10, originalTexture.Width - 20, originalTexture.Height - 20);

Texture2D cropTexture = new Texture2D(GraphicsDevice, sourceRectangle.Width, sourceRectangle.Height);
Color[] data = new Color[sourceRectangle.Width * sourceRectangle.Height];
originalTexture.GetData(0, sourceRectangle, data, 0, data.Length);

Which I’m converting to VB, but my line:
cropTexture = New Texture2D(GR.GraphicsDevice, sourceRectangle.Width, sourceRectangle.Height)

Gives the Error:
SharpDX.SharpDXException was unhandled
Message=HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

My rectangle comes from a routine which calculates the size from a rotated sprite, but I know it’s right as I’ve used it many times before.
(GR is the GraphicsDeviceManager)

Did you check that GR.GraphicsDevice is not null, and that sourceRectangle.Width and sourceRectangle.Height are both greater than zero? Don’t assume they are because it has been used before. The error is telling us that an argument is incorrect, so double check in the debugger that they are what you expect them to be.

Thanks Konaju, it was a problem with the width variable, which in certain circumstances was presented at 0, at which point everything goes pop!

Thanks for the nudge.

Note: It depends on several factors. BUT it might be more efficient to render required area into render target (since you said texture). But as I said, more details would be required, just something for you to consider.

What I needed really was a color array that I could pass to a routine for pixel checking, but that isn’t working quite right, so then I wanted to render the texture to make sure my rotation and matrix code was right. I got the New Texture2d and SetData working in the end.

Every now and then I get an error where it seems there is a memory conflict, reading/writing at the same time, but as soon as I know the testing is complete I’ll remove this code anyway.

I’ll post the problem I’m now having in another topic as it’s a slightly different issue. I think!