Sprites Series: Draw many Sprites from a single Sprite Sheet

With a Sprit sheet you can combine sprite images into larger sheets, so you will only have to load one image to your project and then draw different sprites from it.

In this example the sprite sheet I’m going to use is a simple image named colors.png with four colors to be drawn in different sprites each color, first I have to add it to our project. (Right click to Content—>Add –> existing item)

colors

After adding colors.png to my project, I’m going to create a texture2D to hold my colors.png image and I’m also going to create four rectangles which are going to indicate where in the image colors.png is located each color square so the we can draw them separately:

Texture2D colorsSprite;

Rectangle red = new Rectangle(0, 0, 103, 150);
Rectangle green = new Rectangle(103, 0, 100, 150);
Rectangle yellow = new Rectangle(203, 0, 100, 150);
Rectangle brown = new Rectangle(303, 0, 100, 150);

Then I’m going to load colors.png to my content pipeline:

colorsSprite = this.Content.Load<Texture2D>("colors");

Now I’m ready to draw different sprites from the same colorsSprite like this:

protected override void Draw(GameTime gameTime)
{
     GraphicsDevice.Clear(Color.CornflowerBlue);

     spriteBatch.Begin();

     spriteBatch.Draw(colorsSprite, new Vector2(50.0f, 50.0f), brown, Color.White);
     spriteBatch.Draw(colorsSprite, new Vector2(150.0f, 100.0f), yellow, Color.White);
     spriteBatch.Draw(colorsSprite, new Vector2(250.0f, 150.0f), green, Color.White);
     spriteBatch.Draw(colorsSprite, new Vector2(350.0f, 200.0f), red, Color.White);

     spriteBatch.End();

     base.Draw(gameTime);
}

And the result is this:

colorsSprites

Resources:

SpriteSheetDEMO Source Code

Tool For Building Complex Sprite Sheets Easily

Advertisements