是直接画一条由点(8,6)到(1,1)的线段吗?
我这个是画任意直线的
中点算法:
#include "stdafx.h"
#include "graphics.h"
#include
// 使用中点算法画任意斜率的直线
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);
}
}
}
int main()
{
int x1,y1,x2,y2;
printf("请输入两点坐标x1, y1, x2, y2:");
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
initgraph(640, 480);
Line_Midpoint( x1, y1, x2, y2, WHITE);
getch();
closegraph();
return 0;
}
Bresenham算法:
#include "stdafx.h"
#include "graphics.h"
#include
#include
void line(int x1, int y1, int x2, int y2, int color)
{
int x= x1;
int y= y1;
int dx= abs(x2 - x1);
int dy= abs(y2 - y1);
int s1= x2>x1? 1:-1;
int s2= y2>y1? 1:-1;
int i;
bool interchange= false;
if (dy>dx)
{
int temp= dx;
dx= dy;
dy= temp;
interchange= true;
}
int p= 2*dy-dx;
for(i=1;i { putpixel(x, y, color); if (p>=0) { if (!interchange) y+= s2; else x+= s1; p-= 2 * dx; } if (!interchange) x+= s1; else y+= s2; p+= 2*dy; } } int main(int argc, char* argv[]) { int x1,y1,x2,y2; printf("请输入两点坐标x1, y1, x2, y2:"); scanf("%d%d%d%d", &x1, &y1, &x2, &y2); initgraph(640, 480); line(x1, y1, x2, y2, WHITE); getch(); closegraph(); return 0; } 要记得把这些文件放到同一个目录下: