vẽ đoạn đoạn thẳng
Code:
/*thuat toan midden Point*/
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include <graphics.h>
#include <stdlib.h>
//#define TRUE 1
//#define FALSE 0
typedef struct {
int x,y;
} point;
//typedef unsigned char BOOL;
int MDline(point A,point B, point *KQPT)
{
int x,y,dx,dy,count,i,p;
point tPT;
BOOL f1= FALSE, f2= FALSE;
/*truong hop song song truc toa do*/
if(A.x==B.x)//song song 0Y
{
if(A.y>B.y)
{
tPT=A;
A=B;
B=tPT;
}
for(count=0,y=A.y;y<=B.y;y++)
{
KQPT[count].x=A.x;
KQPT[count++].y=y;
} return count ;
}
if(A.y==B.y)// song song 0X
{
if(A.x>B.x)
{
tPT=A;
A=B;
B=tPT;
}
for(count=0,x=A.x;x<=B.x;x++)
{
KQPT[count].x=A.x;
KQPT[count++].y=x;
} return count ;
}
if(A.x>B.x)
{
tPT=A ;
A=B;
B=tPT;
}
/*he so goc<0*/
if(A.y>B.y)
{
f1=TRUE;
tPT=B;
B.x=2*B.x-A.x;
B.x=A.y;
A=tPT;
}
/*he so goc >1*/
if((B.y-A.y)>(B.x-A.x))
{
f2=TRUE;
x=A.x;
A.x=A.y;
A.y=x;
x=B.x;
B.x=B.y;
B.y=x;
}
/*tinh toan*/
x=A.x;
y=A.y;
dx=B.x-A.x;
dy=B.y-A.y;
p=dy-dx/2;
for(count=0;x<=B.x;x++)
{
KQPT[count].x=x;
KQPT[count++].y=y;
if(p<=0)
{
p+=dy;
}
else
{
y++;
p+=dy-dx;
}
}
/*kiem tra tinh hop le*/
if(f2)
for( i=0;i<count;i++)
{
x=KQPT[i].x;
KQPT[i].x=KQPT[i].y;
KQPT[i].y=x;
}
if(f1)
for(i=0;i<count;i++)
{
KQPT[i].x=2*tPT.x-KQPT[i].x;
}
return count;
}
int main()
{
int i,count;point A,B;
point KQPT[640];
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/*Nhap du lieu*/
// clrscr();
printf("Nhap toa do diem thu nhat:\n");
printf("\nxA="); scanf("%d",&A.x);
printf("\nyA="); scanf("%d",&A.y);
printf("Nhap toa do diem thu hai:\n");
printf("\nxB="); scanf("%d",&B.x);
printf("\nyB="); scanf("%d",&B.y);
/*Khoi dong che do do hoa*/
initgraph(&gdriver, &gmode, "D:\\TC\\BGI");
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
/*Thuc hien ve*/
count= MDline(A,B, KQPT);
for(i= 0; i< count; i++)
putpixel(KQPT[i].x, KQPT[i].y,RED);
/*Ket thuc*/
getch();
closegraph();
}