CODECUBE VENTURES

Drawing Lines with GDI+

In my experiments with making PONG in C#, I wanted to make the ball bounce around more realistically. This is what I came across.

I started looking for ways to move ball around the screen so I could actually adjust it's trajectory based on where it hit on the paddle. The Bresenham line drawing algorithm is apparently THE way to draw lines in an integer based grid. Having experimented in the past with this concept, I was rather amazed to see how complex the actual algorithm is. Just so you know, this isn't even the whole thing. This will only work for lines going top-down/left-right from horizontal to a 45 degree angle. The code below is simple a C# version of the code found here. I'll try to finish the rest of the algorithm soon ... but here it is ... for the first octant of a grid.

void line(Graphics g, int x1, int y1, int x2, int y2, Pen pen)
{
int dx = x2 - x1;
int dy = y2 - y1;

int y = y1;
int eps = 0;
Bitmap bmp = new Bitmap(1,1,g);
bmp.SetPixel(0,0,Color.Black);

for (int x=x1; x<=x2;x++)
{
g.DrawImage(bmp,x,y);

eps+=dy;
if ((eps*2) &rts= dx)
{
y++;
eps-=dx;
}
}

}

Please note that since there's no method for actually drawing a pixel to the screen, I'm simply creating a black 1x1 bitmap, and drawing that. There's probably a faster way, and I'll let you know when I find it.

Latest post: Digging Up the First Version of CodeCube

See more in the archives