I’m writing a map editor for a 2D XNA game and wanted to use a lot of the same code for displaying the map in the editor and in the actual game. However, I wanted the ease of use and familiarity of WinForms for the user interface.
My plan was to have a window that would contain buttons for each ground texture that you could paint with. The background image of each button should represent what texture it will allow you to paint with. Thus, my problem: I needed to put an image that I had in memory as a Texture2D onto the Button that takes System.Drawing.Image. Furthermore, to make the editor more flexible, the Texture2D I have in memory contains all of the possible ground tiles, so I need to only put one small portion of it onto the Button.
I searched and was unable to find a great way to do this, so I came up with this:
private Bitmap GetButtonImage(Microsoft.Xna.Framework.Rectangle tile,
Microsoft.Xna.Framework.Graphics.Texture2D tileTex)
{
int[] data = new int[tile.Width * tile.Height];
tileTex.GetData<int>(0, tile, data, 0, tile.Width * tile.Height);
Bitmap bitmap = new Bitmap(tile.Width, tile.Height);
for (int x = 0; x < tile.Width; ++x)
{
for (int y = 0; y < tile.Height; ++y)
{
Color bitmapColor =
Color.FromArgb(data[y * tile.Width + x]);
bitmap.SetPixel(x, y, bitmapColor);
}
}
return bitmap;
}
The method takes in the Rectangle that contains the part of the texture that you want to get as a Bitmap, and the Texture2D that contains all the ground tiles. It spits out a Bitmap that only contains the part of the texture you wanted.
This could probably be optimized by taking in an array of data, a start index, and an end index so that I only end up calling Texture2D.GetData once, but that would add a bit to the code snippet.

2 Responses to Bitmap from Texture2D