使用VC画图最麻烦的的是要使用putpixel(x, y, c)这个函数;无法导入它的头文件#include <graphics.h>,
这是因为VC环境下没有这个头文件。需要自己在VC安装目录下的include目录下加上graphics.h这个文件。
可以使用EasyX这个软件直接安装,它会直接找到你电脑上VC的安装目录。
要想能在屏幕上画出一条直线,必须要进入绘图模式:
int graphdriver=DETECT, graphmode;
initgraph(&graphdriver, &graphmode, "..\\bgi"); //设置为绘图模式
注意,这个是以图形框左上角为原点坐标,x向右为正,y向下为正。
DDA算法是不能画出斜率不存在的情况的,必须要单独考虑。
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
void DDALine(int x0,int y0,int x1,int y1,int color){
int x;
double dx,dy,y,k;
dx = x1 - x0;
dy = y1 - y0;
k = dy / dx;
y = y0;
for(x = x0;x <= x1;x++){
putpixel(x, int(y + 0.5), color);
y = y + k;
}
}
int main()
{
int x0,y0,x1,y1;
scanf("%d%d%d%d",&x0,&y0,&x1,&y1);
int c=RED;
if(x0 == x1){
int graphdriver=DETECT, graphmode;
initgraph(&graphdriver, &graphmode, "..\\bgi"); //设置为绘图模式
for(int y = y0;y <= y1;y++)
putpixel(x0, y, c);
getch();
closegraph();//恢复文本模式
}
else{
int graphdriver=DETECT, graphmode;
initgraph(&graphdriver, &graphmode, "..\\bgi"); //设置为绘图模式
DDALine(x0, y0, x1, y1, c);
getch();
closegraph();//恢复文本模式
}
return 0;
}