Drawing diagonal lines in SDL

Good Day/Night,

I am currently trying to draw a bunch of lines in a empty SDL window.
I am having diffeculties constructing my DrawLine function so that it will place the pixel in the correct approximate place where the line is going. For horisontal & vertical lines its not a herculean task, but i am having problems in defining the content of my loops within DrawLine.

I am aware of the Bresenham's line algorithm, my problem thereafter is understanding the consept.

Here goes my thoughts so far;
1
2
3
4
5
6
7
8
9
10
11
12
13
void DrawLine(SDL_Surface *screen, int x1, int y1, int x2, int y2, unsigned int color)
{
    int i,j;

    for (i=x1; i<x2; i++)
    	//
    	for(j=y1; j<y2; j++)
    	{
    		if // some statement that determines j & i are infact on line
    			SetPixel(screen, i, m, color);
    	}

}


Now, what i am asking here is wheter or not you can describe the thought prossess behind how to determin where to SetPixel. I am aware of the more complex versions of this function to allow more versetile coordinates for drawing the acctual line.

I am hoping you could shed some light on this issue for me, if you have the time and patience. I am a fast learner, but i just gotta get it right first.

Sincerely, Vladwow
Last edited on
This probably isn't the ideal solution, but....


You can use pythagorean theorum to find the length of a line:

a*a + b*b = c*c

or... to rephrase:

x*x + y*y = length*length

If you divide a vector (line) by its length, you have a 'unit' vector (a line with a length of 1)

You can then step through each point on the line and draw it at the appropriate coords onscreen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double x = x2 - x1;
double y = y2 - y1;
double length = sqrt( x*x + y*y );

double addx = x / length;
double addy = y / length;

x = x1;
y = y1;

for(double i = 0; i < length; i += 1)
{
  SetPixel( (int)x, (int)y, your_color );
  x += addx;
  y += addy;
}
Thats freaking brilliant mate! Absolutly a valid way to draw a line with c in SDL, since this has seemingly no restrictions to in the code to wheter its horrisontal, vertical or diagonal.

This is something i'm absolutly going to remember. Thank you.


Sincerly, Vladwow
Topic archived. No new replies allowed.