怎样用C语言绘制直线
- 提问者网友:放下
- 2021-08-17 17:22
- 五星知识达人网友:玩世
- 2021-08-17 18:22
【C语言的用MoveTo()和LineTo()】
#include<graphics.h>
#include<math.h>
void myline1(int x1,int y1,int x2,int y2,int color)
{
int iTx;
int iTy;
int iDx;
int iDy;
int iFt;
int iSt;
int iXt;
int iYt;
if(y2<y1)
{
iTx=x1;
x1=x2;
x2=iTx;
iTy=y1;
y1=y2;
y2=iTy;
}
iTx=x2-x1;
iTy=y2-y1;
iDx=1;
iDy=1;
iFt=0;
iSt=iTx+iTy;
if(iTx<0)iSt=-1*iTx+iTy;;
iXt=0;
iYt=0;
while(iSt>0)
{
putpixel(x1+iXt,y1+iYt,color);
if(iTx>=0)
{
if(iFt<0)
{
iYt+=iDy;
iFt+=iTx;
}
else
{
iXt+=iDx;
iFt-=iTy;
}
}
else
{
if(iFt<0)
{
iXt-=iDx;
iFt+=iTy;
}
else
{
iYt+=iDy;
iFt+=iTx;
}
}
iSt--;
}
}
int myline2(int x1,int y1,int x2,int y2,int color)
{
int iX;
int iY;
int iTx;
int iTy;
float fDx;
float fDy;
float fMinf;
float fMaxF;
float fS;
fMinf=0.5;
iX=x1;
iY=y1;
putpixel(x1,y1,color);
if(x1==x2&&y1==y2)
{
return(1);
}
iTx=1;
iTy=1;
fDx=(float)(x2-x1);
fDy=(float)(y2-y1);
fMaxF=fDy/fDx>0?fDy/fDx:(-fDy/fDx);
if(fDx<0)iTx=-1;
if(fDy<0)iTy=-1;
fS=fDx>0?fDx:(-fDx);
if(fMaxF==1)
{
iX=x1;
iY=y1;
while(fS>0)
{
iX+=iTx;
iY+=iTy;
putpixel(iX,iY,color);
fS--;
}
}
else if(fMaxF>1)
{
fS+=fDy>0?fDy:(-fDy);
while(fS>0)
{
iY+=iTy;
putpixel(iX,iY,color);
fMinf+=1/fMaxF;
fS--;
if(fMinf>=1)
{
iX+=iTx;
fMinf--;
putpixel(iX,iY,color);
fS--;
}
}
}
else
{
fS+=fDy>0?fDy:(-fDy);
while(fS>0)
{
iX+=iTx;
putpixel(iX,iY,color);
fMinf+=fMaxF;
fS--;
if(fMinf>=1)
{
iY+=iTy;
fMinf--;
putpixel(iX,iY,color);
fS--;
}
}
}
}
【能够画出任意斜率的直线算法程序】
int dx,dy,incrE,incrNE,d,x,y;
if ((point[1].x-point[0].x)==0){ //垂直的直线
x=point[0].x;
for(y=point[0].y;y<point[1].y;y++)
pDC->SetPixel(x,y,50);
}
else if(abs((point[1].y-point[0].y)/(point[1].x-point[0].x))<=1){ //斜率 -1到 1 之间
dx=point[1].x-point[0].x;
dy=point[0].y-point[1].y;
d=dx-2*dy;
incrE=-2*dy;
incrNE=2*(dx-dy);
x=point[0].x,y=point[0].y;
pDC->SetPixel(x,y,50);
if(point[0].y>point[1].y){
while(x<point[1].x)
{
if(d>=0){
d+=incrE;
x++;
}
else
{d+=incrNE;
x++;
y--;
}
pDC->SetPixel(x,y,50);
}
}
else if(point[0].y<=point[1].y){
dy=point[1].y-point[0].y;
incrE=-2*dy;
incrNE=2*(dx-dy);
x=point[0].x,y=point[0].y;
pDC->SetPixel(x,y,50);
while(x<point[1].x)
{
if(d>=0){
d+=incrE;
x++;
}
else
{d+=incrNE;
x++;
y++;
}
pDC->SetPixel(x,y,50);
}
}
}
else { //斜率 <-1 和 >1的直线
if(point[1].x>=point[0].x){
dx=point[1].x-point[0].x;
dy=point[1].y-point[0].y;
d=2*dx-dy;
incrE=2*dx;
incrNE=2*(dx-dy);
x=point[0].x,y=point[0].y;
pDC->SetPixel(x,y,50);
while(x<point[1].x)
{
if(d<0){
d+=incrE;
y++;
}
else
{d+=incrNE;
pDC->SetPixel(x,y,50);
x++;
y++;
}
pDC->SetPixel(x,y,50);
}
}
else if((point[1].y-point[0].y)/(point[1].x-point[0].x)<-1){
dx=point[1].x-point[0].x;
dy=point[0].y-point[1].y;
d=2*dx-dy;
incrE=2*dx;
incrNE=2*(dx-dy);
x=point[0].x,y=point[0].y;
pDC->SetPixel(x,y,50);
while(y<point[1].y)
{
if(d>0){
d+=incrE;
y++;
}
else
{d+=incrNE;
x--;
y++;
}
pDC->SetPixel(x,y,50);
}
}
}
- 1楼网友:洒脱疯子
- 2021-08-17 19:05