要兼顾8个方向的源程序。
语言不限(最好用graphic图形库),自己也写了个,但是在其他象限上仍然有些问题。
学图形学时候写的。。。看看吧TC2.0运行通过,三种算法,第三种我用中点分割做的, 不知道和你所说的中点是不是一样的
#include<math.h>
#include<dos.h>
#include<stdio.h>
#include<graphics.h>
main(){
void DDAline(int,int,int,int);
void Bline(int,int,int,int);
void MiddlePoint(int,int,int,int);
int gd=VGA,gm=VGAHI;
int i=1;
int x1,y1,x2,y2,n;
float a1,a2,r;
struct time runtime1,runtime2,runtime3,runtime4,runtime5,runtime6;
initgraph(&gd,&gm,"c:\\tc");
setcolor(12);
printf("StartPoint and EndPoint:");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
line(0,240,640,240);
line(320,0,320,480);
gettime(&runtime1);
for(i=1;i<10;i++){
DDAline(x1,y1,x2,y2);
DDAline(-x1,y1,-x2,y2);
DDAline(x1,-y1,x2,-y2) ;
DDAline(-x1,-y1,-x2,-y2);
DDAline(y1,x1,y2,x2);
DDAline(-y1,x1,-y2,x2);
DDAline(y1,-x1,y2,-x2);
DDAline(-y1,-x1,-y2,-x2);
}
gettime(&runtime2);
getch();
gettime(&runtime3);
for(i=1;i<10;i++){
Bline(x1,y1,x2,y2);
Bline(-x1,y1,-x2,y2);
Bline(x1,-y1,x2,-y2);
Bline(-x1,-y1,-x2,-y2);
Bline(y1,x1,y2,x2);
Bline(-y1,x1,-y2,x2);
Bline(y1,-x1,y2,-x2);
Bline(-y1,-x1,-y2,-x2);
}
gettime(&runtime4);
getch();
gettime(&runtime5);
for(i=1;i<10;i++){
MiddlePoint(x1,y1,x2,y2);
MiddlePoint(-x1,y1,-x2,y2) ;
MiddlePoint(x1,-y1,x2,-y2) ;
MiddlePoint(-x1,-y1,-x2,-y2) ;
MiddlePoint(y1,x1,y2,x2) ;
MiddlePoint(-y1,x1,-y2,x2) ;
MiddlePoint(y1,-x1,y2,-x2) ;
MiddlePoint(-y1,-x1,-y2,-x2);
}
gettime(&runtime6);
printf("\n\n\n\n DDA begin: %d %d\n",runtime1.ti_sec,runtime1.ti_hund);
printf(" DDA end: :%d %d\n",runtime2.ti_sec,runtime2.ti_hund);
printf(" B begin: :%d %d\n",runtime3.ti_sec,runtime3.ti_hund);
printf(" B end: :%d %d\n",runtime4.ti_sec,runtime4.ti_hund);
printf(" Mid begin: :%d %d\n",runtime5.ti_sec,runtime5.ti_hund);
printf(" Mid end: :%d %d\n",runtime6.ti_sec,runtime6.ti_hund);
getch(); closegraph();
}
void DDAline(int x1,int y1,int x2,int y2){
int steps,i;
float dx,dy,x,y;
x=x1+0.5;y=y1+0.5;
steps=abs(x2-x1)>=abs(y2-y1)?abs(x2-x1):abs(y2-y1);
dx=(float)(x2-x1)/steps;
dy=(float)(y2-y1)/steps;
for(i=0;i<=steps;i++){
putpixel((int)(320+x),(int)(240-y),4);
x+=dx;y+=dy;
}
}
void Bline(int x1,int y1,int x2,int y2){
int e,dx,dy,x,y,i,xsign,ysign,interchange=0,temp;
x=x1;y=y1;
dx=abs(x2-x1);
dy=abs(y2-y1);
if(dx<dy){
temp=dx;dx=dy;dy=temp;interchange=1;}
xsign=(x1<x2)?1:-1;
ysign=(y1<y2)?1:-1;
e=-dx;
for(i=0;i<=dx;i++){
putpixel(320+x,240-y,15);
e+=2*dy;
if(e>=0){
e-=2*dx;
if(interchange)
x+=xsign;
else
y+=ysign;
}
if(interchange)
y+=ysign;
else x+=xsign;
}
}
void MiddlePoint(int x1,int y1,int x2,int y2){//中点分割
int x,y;
if(abs(x1-x2)>1&&abs(y1-y2)>1){
x=(x1+x2)/2;
y=(y1+y2)/2;
putpixel(320+x,240-y,30);
MiddlePoint(x1,y1,x,y);
MiddlePoint(x,y,x2,y2);
}
}