-
Line drawing routine
I'm using the SDL for graphics. and i am trying to write a function for drawing a line,
this is what i came up with
When angles are extreem it doesnt draw quite right. i helped with problem by drawing calculattes x.00 -> x1 x.00 to garner more y coordinates too use, still didnt help to much
any ideas on a better way to code this?
Code:
void Artist::drawLine(int f, int p, int u , int t, Uint8 r, Uint8 g, Uint8 b)
{
float rise = (p * 1.0) - (t * 1.0);
float run = (f * 1.0) - (u * 1.0);
float slope = rise / run;
float y,x, d;
d = (slope * f ) - p ;
for ( f = f * 100, u = u * 100; f <= u; f ++)
{
drawPixel(surface, f / 100 , ( (f*slope) + d ) / 100, r,g,b);
}
}
-
Code:
void Line(Video *Device,int x,int y,int x2,int y2,DWORD color)
{
int eterm=0;
int length=0;
int diffx=x2-x;
int diffy=y2-y;
int stepx=1;
int stepy=Device->GetBufferPitch();
DWORD offset=(y*stepy)+x;
if (diffx<0)
{
stepx=-stepx;
diffx=-diffx;
}
if (diffy<0)
{
stepy=-stepy;
diffy=-diffy;
}
if (diffx>diffy)
{
length=diffx+1;
for (int i=0;i<length;i++)
{
Video->Buffer[offset]=color;
offset+=stepx;
eterm+=diffy;
if (eterm>diffx)
{
eterm-=diffx;
offset+=stepy;
}
}
}
else
{
length=diffy+1;
for (int i=0;i<length;i++)
{
Video->Buffer[offset]=color;
offset+=stepy;
eterm+=diffx;
if (eterm>0)
{
eterm-=diffx;
offset+=stepy;
}
}
}
}
There are other variations of this algorithm known as Bresehnam's algorithm.
-
and another...
Code:
/* Draw line from x1, y1 to x2, y2 using Bresenham's Algorithm */
void bresenhamLine(const int x1, const int y1, const int x2, const int y2) {
int dx = (x1 <= x2) ? x2 - x1 : x1 - x2;
int dy = (y1 <= y2) ? y2 - y1 : y1 - y2;
int x = x1;
int y = y1;
int e = 0;
int xInc = (x1 <= x2) ? 1 : -1;
if(x1 == x2)
xInc = 0;
int yInc = (y1 <= y2) ? 1 : -1;
if(y1 == y2)
yInc = 0;
if(dy <= dx) {
/* x iterative loop */
for( ; (xInc*x <= xInc*x2) && (yInc*y <= yInc*y2); x += xInc ) {
setPixel(x,y);
e += dy;
if( yInc && (2*e + yInc*dy) >= xInc*dx ) {
y += yInc;
e -= dx;
}
}
}
else {
/* y iterative loop */
for( ; (yInc*y <= yInc*y2) && (xInc*x <= xInc*x2); y += yInc ) {
setPixel(x,y);
e += dx;
if( xInc && (2*e + xInc*dx) >= yInc*dy ) {
x += xInc;
e -= dy;
}
}
}
}