Friday, August 20, 2010

Drawing lines and rectangles in XNA

In my last project, I needed a way to draw a grid with lines in XNA but I had some trouble in actually finding a way how to draw a simple line.  In this post, I will explain how to accomplish this.

First, create a new Texture2D with size: 1x1

Texture2D pixel = new Texture2D(GraphicsDevice, 1, 1, 1, TextureUsage.None, SurfaceFormat.Color);

You can access the GraphicsDevice from your Game (game.GraphicsDevice)

We then set the colour of this 1x1 texture to White. This allows us to choose what colour it should be drawn later on.

pixel.SetData(new[] { Color.White });

Now we can draw this texture by specifying a Rectangle holding the position and size:

spriteBatch.Draw(pixel, new Rectangle(10, 20, 100, 50), Color.DarkGreen);

The above snippet will draw a dark green 100x50 rectangle at {X: 10, Y: 20}