Entity
Entity

Reputation: 8212

Crop Texture2D Spritesheet

I'm developing a game which will have spritesheets, like so:

E.G of spritesheet

I know when you do spriteBatch.Draw(...) you can draw a certain portion of the image, but for what I'm doing, I need to have a separate Texture2D object per frame.

I've done google searches, but all I can find is outdated code :/

UPDATE The code posted by MJP here is very nearly what I need... however, there isn't a RenderTarget2D.GetTexture() function in XNA 4.0.

Upvotes: 1

Views: 3126

Answers (1)

Entity
Entity

Reputation: 8212

Wow ok... A whole lot more google searching revealed:

Texture2D tex = (Texture2D)renderTarget;

Just a simple cast :)

Here's my final code:

    public static Texture2D Crop(Texture2D image, Rectangle source)
    {
        var graphics = image.GraphicsDevice;
        var ret = new RenderTarget2D(graphics, source.Width, source.Height);
        var sb = new SpriteBatch(graphics);

        graphics.SetRenderTarget(ret); // draw to image
        graphics.Clear(new Color(0, 0, 0, 0));

        sb.Begin();
        sb.Draw(image, Vector2.Zero, source, Color.White);
        sb.End();

        graphics.SetRenderTarget(null); // set back to main window

        return (Texture2D)ret;
    }

Upvotes: 5

Related Questions