最近上课在学计算机图形学,第一个实验是用Bresenham算法画直线(可画出各种长度、宽度、斜率的直线),代码如下:
#include
#include
#include
void lineBres(int x0,int y0,int xend,int yend,unsigned int width);
int main()
{
initwindow(640,480); //open a 640x480 graphics window
lineBres(320,240,400,460,2);
lineBres(320,240,520,440,2);
lineBres(320,240,520,400,2);
lineBres(320,240,520,240,2);
lineBres(320,240,350,190,2);
lineBres(320,240,560,0,2);
lineBres(320,240,520,200,2);
lineBres(320,240,320,20,2);
lineBres(320,240,20,40,2);
lineBres(320,240,120,40,2);
lineBres(320,240,130,190,2);
lineBres(320,240,50,240,2);
lineBres(320,240,50,270,2);
lineBres(320,240,90,470,2);
lineBres(320,240,20,480,2);
lineBres(320,240,320,440,2);
getch(); //wait for user to press a key
closegraph(); //close graphics window
return 0;
}
void lineBres(int x0,int y0,int xend,int yend,unsigned int width)
{
int dx = fabs(xend - x0),dy = fabs(yend - y0);
int p = 2 * dy - dx;
int c1 = 2 * dy, c2 = 2 * (dy - dx);
int x,y;
//特殊情况 :平行于Y轴
if(x0 == xend)
{
int temp = y0>yend?yend:y0;
for(int i = 0;i < dy; i++,temp++)
for(int j = 0; j < width ; j++)
putpixel(x0 + j,temp,RGB(0,255,0));
return;
}
double k =double(yend - y0) / double(xend - x0);
if(x0 > xend)
{
x = xend;
y = yend;
xend = x0;
}
else
{
x = x0;
y = y0;
}
if(k != 0)
for(int i = 0; i < width ; i++)
putpixel(x + i,y,RGB(0,255,0));
else
for(int i = 0; i < width ; i++)
putpixel(x,y + i,RGB(0,255,0));
while(x < xend)
{
x++;
if(p < 0)
{
p += c1;
}
else
{
if(k>=0 && k <=1)
y++;
else if(k > 1)
y += (k + 0.5);
else if(k<0 && k>=-1)
y--;
else if( k < -1)
y += (k-0.5);
p += c2;
}
if(k != 0)
for(int i = 0; i < width ; i++)
putpixel(x + i,y,RGB(0,255,0));
else
for(int i = 0; i < width ; i++)
putpixel(x,y + i,RGB(0,255,0));
}
}