线型算法(计算机图形学)

时间:2022-11-08 08:40:15
#include<graphics.h>
#include<conio.h>

//Bresenham画线算法
void BresenhamLine(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 ShortLine(int x0,int y0,int x1,int y1,int color){

int x,y,dx,dy,e;
int linkmark[12]={1,1,1,1,1,1,1,1,1,0,0,0};
dx=x1-x0;
dy=y1-y0;
e=-dx;
x=x0;
y=y0;
for(int i=0;i<=dx;i++){
if(linkmark[i%12]==1){
putpixel(x,y,color);
}
x=x+1;
e=e+2*dy;
if(e>=0){
y=y+1;
e=e-2*dx;
}
}
}

//画点横线
void PointShortLine(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;
int linkmark[20]={1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0};
for(int i=0;i<=dx;i++){
if(linkmark[i%20]==1){
putpixel(x,y,color);
}
x=x+1;
e=e+2*dy;
if(e>=0){
y=y+1;
e=e-2*dx;
}
}
}

// 中点画圆法
void Circle_Midpoint(int x, int y, int r, int color,int flag)
{
int tx = 0, ty = r, d = 1 - r;
while(tx <= ty)
{
// 利用圆的八分对称性画点
if(flag==0){
putpixel(x + tx, y + ty, color);
putpixel(x - tx, y + ty, color);
putpixel(x + ty, y + tx, color);
putpixel(x - ty, y + tx, color);
}
else{
putpixel(x + tx, y - ty, color);
putpixel(x - tx, y - ty, color);
putpixel(x + ty, y - tx, color);
putpixel(x - ty, y - tx, color);
}

if(d < 0)
d += 2 * tx + 3;
else
d += 2 * (tx - ty) + 5, ty--;

tx++;
}
}

//画波浪线
void WaveLine(int x0,int y0,int x1,int y1,int color){

//初始化图符即半圆的信息
int flag=1;
int r=2;
int dx=x1-x0;
int y=y0;
int x=x0+r;
while(x<=dx){
if(flag==1){
Circle_Midpoint(x,y,r,RED,1);
flag=0;
}
else{
Circle_Midpoint(x,y,r,RED,0);
flag=1;
}
x+=2*r;
}
}

void main(){

int gdriver=DETECT, gmode;
initgraph(&gdriver,&gmode,"");//根据测试结果初始化图形界面

//画直线
BresenhamLine(10,80,500,80,RED);

//画短横线
ShortLine(10,120,500,120,RED);

//画点横线
PointShortLine(10,160,500,160,RED);

//画波浪线
WaveLine(10,200,500,200,RED);


// 按任意键退出
getch();
closegraph();
}

线型算法(计算机图形学)