I'm trying to split a tileset (from here) into individual tiles.
For debugging purposes I wrote some code to split the tileset into individual tiles and display them on screen, but some aren't being split correctly.
There are some small icons after the mob in the 3rd line from the bottom that got mixed up because they seemed to be smaller than 32x32. Here is my code for splitting them:
public class TilesetEngine : Game
{
Dictionary<int, Texture2D> individualTiles = new Dictionary<int, Texture2D>();
public void LoadTiles(string szFileName, ContentManager content, GraphicsDevice graphicsDevice)
{
var foo = content.Load<Texture2D>(szFileName);
Color[] imageData = new Color[foo.Width * foo.Height];
foo.GetData<Color>(imageData);
var horizontalElements = foo.Width / 32;
var verticalLines = foo.Height / 32;
var i = 0;
for (int y = 0; y < verticalLines; y++)
{
for (int x = 0; x < horizontalElements; x++)
{
var startRect = new Rectangle(x * 32, y * 32, 32, 32);
var colorPiece = getImageData(imageData, foo.Width, startRect);
var subTexture = new Texture2D(graphicsDevice, 32, 32);
subTexture.SetData<Color>(colorPiece);
individualTiles.Add(i, subTexture);
i++;
}
}
}
public IEnumerable<Texture2D> GetTiles()
{
return individualTiles.Values.AsEnumerable<Texture2D>();
}
Color[] getImageData(Color[] colorData, int width, Rectangle rectangle)
{
var color = new Color[rectangle.Width * rectangle.Height];
for (int x = 0; x < rectangle.Width; x++)
for (int y = 0; y < rectangle.Height; y++)
color[x + y * rectangle.Width] = colorData[x + rectangle.X + (y + rectangle.Y) * width];
return color;
}
}
Usage
tileEngine = new TilesetEngine();
tileEngine.LoadTiles("fantasy-tileset", Content,GraphicsDevice);
Drawing code
spriteBatch.Begin();
int i = 0;
int padding = 10;
var tiles = tileEngine.GetTiles();
var maxPerLine = 10;
var count = 0;
var vertLine = 0;
foreach (var p in tiles)
{
spriteBatch.Draw(p, new Rectangle(count * 32 + padding * count, vertLine * 32 + padding * vertLine, p.Width, p.Height), Color.White);
count++;
if (count == maxPerLine)
{
count = 0;
vertLine++;
}
}
spriteBatch.End();
I don't believe this is the best way, since I always found tilesets with pictures with variable size, what would be the best way to detect an individual tile from a tileset and split it?
sourceRectangle
parameter toSpriteBatch.Draw
\$\endgroup\$