I want to be able to take a single image and cut them up into a lot of images to make the sprites. How would I do that in XNA since I only know how to load the texture then use it without changing it?


2 Answers 2


If you want to cut up a single texture into multiple textures in 2D you can just use the 'SourceRectangle' overload from SpriteBatch.Draw. The SourceRectangle specifies which part of the texture to draw at 'DestinationRectangle'. This is especially useful when using sprite sheets.

See MSDN for further details: http://msdn.microsoft.com/en-us/library/ff433992.aspx


Here is some code that illustrates how to do what you want. As the others have suggested it uses the SourceRectangle overload on the SpriteBatch Draw method.

Imagine you have a square texture 120px x 120px and it contains 9 sprites, each 40px x 40px. We want to draw the one in the bottom right hand corner.

Within the texture, the (x, y) coordinate of the top left corner of this sprite would be (80, 80). Also, we know the width and height of the sprite is 40 pixels.

First we need to define a new instance of Rectangle that holds this top left position along with the width and height.

A rectangle constructor takes in (x, y, width, height) so we would define the source rectangle as follows:

Rectangle mySourceRect = new Rectangle(80, 80, 40, 40); //x=80, y=80, width=40, height=40

You also need a Texture2D into which you have loaded your 9x9 texture. Finally you need a Vector2 which holds the position.

Then you simply make your Draw call as follows:

spriteBatch.Draw(myTexture, myPosition, mySourceRect, Color.White);

This should draw the bottom right 40 pixel square of the larger texture. To draw the other sections of the texture you would simply change the x and y coordinates used in the source rectangle.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .