Home > Development, WP7 Development > How To: Draw A Line in XNA for WP7

## How To: Draw A Line in XNA for WP7

While working on my most recent game (super top secret!) I realized there was no drawLine function in XNA… At least, not an easy to use one! So I asked my Digipen friend about it (after attempting to derive my own formula) and he gave me this particularly useful link;

http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm

I quickly converted the psuedo-code into C# and came up with these two functions. Enjoy! I haven’t really had to time to logically step through it but essentially the gist(from what I understand) is that it determines where to place a “pixel” image based on the slope using a specific pattern that looks really good.

I recommend using a circular, 8x8ish texture for the pixel you use to render. Here is the code!

private void DrawLine(SpriteBatch spriteBatch, float x0, float y0, float x1, float y1)

{

bool steep = (Math.Abs(y1 – y0) > Math.Abs(x1 – x0));

if (steep)

{

Swap(ref x0, ref y0);

Swap(ref x1, ref y1);

}

if (x0 > x1)

{

Swap(ref x0, ref x1);

Swap(ref y0, ref y1);

}

float deltax = x1 – x0;

float deltay = Math.Abs(y1 – y0);

float error = 0;

float deltaerror = deltay / deltax;

int ystep;

float y = y0;

ystep = (y0 < y1) ? 1 : -1;

for(float x = x0; x < x1; x++)

{

Vector2 position;

if (steep)

position = new Vector2(y, x);

else

position = new Vector2(x, y);

spriteBatch.Draw(pixelTexture, position, Color.White);

error += deltaerror;

if (error >= 0.5f)

{

y = y + ystep;

error -= 1.0f;

}

}

}

private void Swap(ref float a, ref float b)

{

float temp = a;

a = b;

b = temp;

}

Hope this helps! 🙂