zomgistania

Main page | About | Articles | Previous Posts | Archives

Thursday, May 18, 2006

Generating textures on-the-fly

I needed something to debug my pathfinding. I wanted to see how it advances when finding the path to a tile.

I thought... "I'll have it set the tile's texture to something else to see when it's doing what tile"... Okay. I made a bunch of graphics with a number on them and a counter on the pathfinder which changed the texture to one with a same number as the current loop was.

At first I had five numbered textures.. then I needed more. It was kind of tedious to create them in paint so I figured.. you can create a Texture from a Bitmap... What if I created the bitmap on the fly.. with GDI!

Ta-dah, I present you: generating textures on the fly with System.Drawing-classes.
The following example is "Using" System.Drawing and Microsoft.DirectX.Direct3D namespaces so if you can't find the classes, they should be somewhere in those.


//First, create a new Bitmap
Bitmap bmp = new Bitmap(20, 20);

//Create pens for drawing
//A black one for text
Pen p = new Pen(Color.Black);

//A white one for background
Pen p2 = new Pen(Color.White);

//Create a Graphics object from the Bitmap
//Dont worry, you can use a Bitmap even though
//it says Image in the parameter list
Graphics g = Graphics.FromImage(bmp);

//Create a font
System.Drawing.Font font = new System.Drawing.Font(
System.Drawing.FontFamily.GenericSerif,10);

//Create a Rectangle for filling the whole bitmap
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);


//Fill with white
g.FillRectangle(p2.Brush, rect);

//Draw some text with black in the top corner
g.DrawString("10", font, p.Brush, 1, 1);


//Now create a texture from the bitmap and you're done!
Texture t = new Texture(device, bmp, 0, Pool.Managed);


Now obviously this isn't very fast. Actually not fast at all... but it can be used for purproses like I did when the speed is not a problem.

0 Comments:

Post a Comment

<< Home