Code:
#include<graphics.h>
#include<math.h>
#include<dos.h>
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void khoitao()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "C:\\tc\\bgi");//Duong dan den thu muc bgi
errorcode = graphresult();
if (errorcode != grOk)
{
cout<<"\n Graphics error: "<<grapherrormsg(errorcode)
<<"\n Press any key to halt:";
getch();
exit(1);
}
}
//===============VE DUONG THANG VOI THUAT TOAN MIDPOINT==================
void midpoint(int x1,int y1,int x2,int y2,int val)
{
int tx=x2-x1,ty=y2-y1;
if (tx>=0)
if (ty>=0)
if (ty>=tx)//goc 2
{
int tg = x1; x1 = y1; y1 = tg;
tg = x2; x2 = y2; y2 = tg;
}
else endl;
else //if (ty<0)
if(tx>=-ty)//goc 8
{
y1 = -y1;
y2 = -y2;
}
else //if(-ty>tx && tx>0 && ty<0)//goc 7 doi xung voi goc 3 qua goc
{
x1 = -x1; x2 = -x2;
int tg = x1; x1 = y1; y1 = tg;
tg = x2; x2 = y2; y2 = tg;
int tg1 = x1, tg2 = y1;
x1 = x2; y1 = y2;
x2 = tg1; y2 = tg2;
}
if(tx<0)
if(ty>0)
if(ty>=-tx)// && tx<0 && ty>0)//goc 3 tinh thong qua goc 4
{
x1 = -x1; x2 = -x2;
int tg = x1; x1 = y1; y1 = tg;
tg = x2; x2 = y2; y2 = tg;
}
else
//if(-tx>ty && ty>0 && tx<0)//goc 4
{x1=-x1;x2=-x2;}
else
if(-ty>=-tx)// && tx<0 && ty<0)//goc 6
{
int tg = x1; x1 = y1; y1 = tg;
tg = x2; x2 = y2; y2 = tg;
int tg1 = x1, tg2 = y1;
x1 = x2; y1 = y2;
x2 = tg1; y2 = tg2;
}
else
// if(-tx>-ty && ty<0 && tx<0)//goc 5
{
int tg1 = x1, tg2 = y1;
x1 = x2; y1 = y2;
x2 = tg1; y2 = tg2;
}
int dx=x2-x1,dy=y2-y1;
int d=dy-dx/2,x=x1,y=y1;
while(x<x2)
{
if(d<=0) d+=dy;
else{d+=dy-dx;y++;}
++x;
if ((ty>=tx && tx>=0 && ty>=0)||(-ty>=-tx && tx<0 && ty<0)) putpixel(y,x,val);//goc 2 va goc 6
else if (tx>=-ty && tx>0 && ty<0) putpixel(x,-y,val);//goc 8
else if ((ty>=-tx && tx<0 && ty>0)||(-ty>=tx && tx>=0 && ty<=0)) putpixel(-y,x,val);//goc 3 va goc 7
else if (-tx>=ty && tx<0 && ty>0) putpixel(-x,y,val);//goc 4
else putpixel(x,y,val);//goc 1 va goc 5
}
}
void main()
{
khoitao();
clrscr();
cleardevice();
setbkcolor(0);
int x1,y1,x2,y2,c;
cout<<"\n Nhap toa do dinh dau (x1,y1): ";cin>>x1;cout<<" ";cin>>y1;
cout<<"\n Nhap toa do dinh cuoi (x2,y2): ";cin>>x2;cout<<" ";cin>>y2;
cout<<"\n Mau ve: ";cin>>c;
clrscr();
cleardevice();
setbkcolor(0);
midpoint(x1,y1,x2,y2,c);
getch();
}
Từ đó các bạn hãy thử phát triển nó thành một hình chữ nhật rùi tô màu cho hình chữ nhật đó nhé ! 