I've been talking with a guy on the creator forums lately about SpriteSheets and so I decided it might be a good idea to post my SpriteSheet class.
-
It's very simple. Only reads sprites from left to right and assumes all Sprites are the same width and height.
-
#region Using
-using System;
-using Microsoft.Xna.Framework;
-using Microsoft.Xna.Framework.Graphics;
-#endregion
-
-namespace Snow.Xna.Graphics
-{
-
-
-
- public class SpriteSheet
- {
- #region Fields
-
- string name;
-
- Texture2D texture;
-
- Rectangle[] rectangles;
-
- int spriteWidth, spriteHeight;
-
- #endregion
-
- #region Properties
-
-
-
-
- public string Name
- {
- get { return name; }
- }
-
-
-
-
- public Texture2D Texture
- {
- get { return texture; }
- }
-
-
-
-
-
-
- public Rectangle this[int i]
- {
- get { return rectangles[i]; }
- }
-
-
-
-
- public int Count
- {
- get { return rectangles.Length; }
- }
-
-
-
-
- public int Width
- {
- get { return texture.Width; }
- }
-
-
-
-
- public int SpriteWidth
- {
- get { return spriteWidth; }
- }
-
-
-
-
- public int Height
- {
- get { return texture.Height; }
- }
-
-
-
-
- public int SpriteHeight
- {
- get { return spriteHeight; }
- }
-
- #endregion
-
-
-
-
-
-
-
- public SpriteSheet(string name, Texture2D texture, int spriteWidth, int spriteHeight)
- : this(name, texture, spriteWidth, spriteHeight, 0)
- {
- }
-
-
-
-
-
-
-
-
- public SpriteSheet(string name, Texture2D texture, int spriteWidth, int spriteHeight, int count)
- {
- this.name = name;
- this.texture = texture;
- this.spriteWidth = spriteWidth;
- this.spriteHeight = spriteHeight;
-
- if(count == 0)
- {
- int numX = texture.Width / spriteWidth;
- int numY = texture.Height / spriteHeight;
-
- rectangles = new Rectangle[numX * numY];
- }
- else
- {
- rectangles = new Rectangle[count];
- }
-
- int x = 0, y = 0;
- for(int i = 0; i < rectangles.Length; i++)
- {
- rectangles[i] = new Rectangle(x, y, spriteWidth, spriteHeight);
-
- x += spriteWidth;
- if(x >= texture.Width)
- {
- x = 0;
- y += spriteHeight;
- }
- }
- }
-
- public static implicit operator Texture2D(SpriteSheet spriteSheet)
- {
- return spriteSheet.Texture;
- }
- }
-}
-
-
You can create a new SpriteSheet and use it like this:
-
`
-
SpriteSheet spriteSheet = new SpriteSheet("tiles", Content.Load<texture2D>("tiles"), 64, 64);
-
-spriteBatch.Begin();
-
-spriteBatch.Draw(spriteSheet,
- new Rectangle(0, 0, spriteSheet.SpriteWidth, spriteSheet.SpriteHeight),
- spriteSheet[0],
- Color.White);
-
-spriteBatch.End();
-
-
`
-
Which loads a spritesheet with sprites of size 64x64. It then draws the first Sprite in the SpriteSheet. You of course wouldn't want to load the spritesheet every frame as well.
-
Feel free to use this code without restriction.
-
Edit: I copied and pasted the second piece of code from somewhere else so I fixed two typos.