Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello

I tried to draw strait line using dda algorithm. I wrote code in c editor using c language.
I use following points to draw the different type of strait line.

I made one function dda in which I write the code to implement dda.
I want to draw four line and I passed following points in function call.
Function argument in sequence
xa, ya ,xb ,yb

1) 10,10,30,10. That line draw properly.
2) 10,10,10,30. That line draw properly.
3) 10,10,20,20. That line draw properly.
4) but for the points 50,10,40,20 line is drawn but it is wrong.
I trace the program and get to know that x and y is increased by 1 each time.but actually it should x should decrease and y should increase. But dda algorithm has no facility for this type of line. Then what should I do??

What I have tried:

C++
#include <stdio.h>
#include <math.h>
#include <graphics.h>
#include <conio.h>
#define r1(a) (a+0.5)
int gdrivers=DETECT,gmode;
void dda(int xa,int ya,int xb,int yb);
void main()
{
	initgraph(&gdrivers,&gmode,"c:\\tc\\bgi");
    	setcolor(BLUE);	
	dda(10,10,30,10);
	dda(10,10,10,30);
	dda(10,10,20,20);
	dda(50,10,40,20);
   	getch();
}
void dda(int xa,int ya,int xb,int yb)
{
	int x, y;
	float xincr,yincr,xp,yp;
	int k,steps,dx,dy;
	float temp;
	dx = abs(xa-xb);
	dy = abs(ya-yb);

	if(dx > dy)	{
		steps=dx;}
	else{
		steps=dy;	}
	temp = (float)(steps);
	xincr=dx/temp;
	yincr=dy/temp;
	x = xa;
	y = ya;
	putpixel(x,y,4);
	xp = x;
	yp = y;
	for(k=0;k<steps;k++)
	{
		xp+=xincr;
		yp+=yincr;
		x = r1(xp);
		y = r1(yp);
		putpixel(x,y,4);
	}
}
Posted
Updated 4-Aug-19 8:35am
v5
Comments
Patrice T 4-Aug-19 13:57pm    
Show your code !
An@mik@ 4-Aug-19 14:08pm    
I improve my question and write the code.
An@mik@ 4-Aug-19 14:15pm    
for last call of dda it show the wrong output

1 solution

Quote:
Then what should I do?

First of all I would change the test data to draw the 12 lines of a clock from the center, just to cover any possibility.
C++
dx = abs(xa-xb); // because of abs here
dy = abs(ya-yb); // and here

if(dx > dy)  {
    steps=dx;}
else{
    steps=dy;   }
temp = (float)(steps);
xincr=dx/temp; // the increments are loosing the direction of drawing
yincr=dy/temp; // and this 1 too

Your code work only in 1 quadrant.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900