emil1000123
emil1000123

Reputation: 11

(XNA) Make a new Texture2D out of another Texture2D

I want to separate an image into multiple texture2ds using a for loop.

https://puu.sh/wu16F/44bef38289.png

I want to do something like this:

newTexture = Texture2D.CopyImage(biggerTexture, x, y, width, height);

Is it possible to do this?

Upvotes: 1

Views: 2308

Answers (2)

Max Play
Max Play

Reputation: 4037

Have you thought about using GetData and SetData?

I just wrote an extension method for testing purposes:

public static class TextureExtension
{
    /// <summary>
    /// Creates a new texture from an area of the texture.
    /// </summary>
    /// <param name="graphics">The current GraphicsDevice</param>
    /// <param name="rect">The dimension you want to have</param>
    /// <returns>The partial Texture.</returns>
    public static Texture2D CreateTexture(this Texture2D src, GraphicsDevice graphics, Rectangle rect)
    {
        Texture2D tex = new Texture2D(graphics, rect.Width, rect.Height);
        int count = rect.Width * rect.Height;
        Color[] data = new Color[count];
        src.GetData(0, rect, data, 0, count);
        tex.SetData(data);
        return tex;
    }
}

You can now call it like so:

newTexture = sourceTexture.CreateTexture(GraphicsDevice, new Rectangle(50, 50, 100, 100));

If you just want to draw a part of the texture, you could use the SpriteBatch overload like domi1819 suggested.

Upvotes: 2

Domi
Domi

Reputation: 292

The only thing that comes to my mind is using Texture2D.FromStream() but that reads a whole image file so it won't really work in your case.

What I did for one of my games is create a wrapper around Texture2D that only draws specific parts of the texture using a SpriteBatch.Draw() overload that accepts source and destination rectangles.

Upvotes: 0

Related Questions