#include <graphics.h>
#include <conio.h>
#include <iostream.h>
// 使用中点算法画任意斜率的直线(包括起始点,不包括终止点)
void Line_Midpoint(int x1, int y1, int x2, int y2, int color)
{
int x = x1, y = y1;
int a = y1 - y2, b = x2 - x1;
int cx = (b >= 0 ? 1 : (b = -b, -1));
int cy = (a <= 0 ? 1 : (a = -a, -1));
putpixel(x, y, color);
int d, d1, d2;
if (-a <= b) // 斜率绝对值 <= 1
{
d = 2 * a + b;
d1 = 2 * a;
d2 = 2 * (a + b);
while(x != x2)
{
if (d < 0)
y += cy, d += d2;
else
d += d1;
x += cx;
putpixel(x, y, color);
}
}
else // 斜率绝对值 > 1
{
d = 2 * b + a;
d1 = 2 * b;
d2 = 2 * (a + b);
while(y != y2)
{
if(d < 0)
d += d1;
else
x += cx, d += d2;
y += cy;
putpixel(x, y, color);
}
}
}
//Bresenham画线算法
void Interger_Bresenham_Line(int x0,int y0,int x1,int y1,int color){
int x,y,dx,dy,e;
dx=x1-x0;
dy=y1-y0;
e=-dx;
x=x0;
y=y0;
for(int i=0;i<=dx;i++){
putpixel(x,y,color);
x=x+1;
e=e+2*dy;
if(e>=0){
y=y+1;
e=e-2*dx;
}
}
}
// 主函数
void main()
{
// 输入起点和终点
int x1,y1,x2,y2;
cout<<"请输入起点:";
cin>>x1>>y1;
cout<<"请输入终点:";
cin>>x2>>y2;
x1=x1+250;
y1=250-y1;
x2=x2+250;
y2=250-y2;
//初始化屏幕大小
initgraph(500, 500);
// 测试画线
Line_Midpoint(0, 250, 500, 250, RED);//x轴
Line_Midpoint(250, 0, 250, 500, RED);//y轴
Interger_Bresenham_Line(300,200,400,250,YELLOW);
// 按任意键退出
getch();
closegraph();
}