在MFC中用bresenham算法画直线,结果画出了折线,求解释!
void CcgdemoView::OnBresenhamLine(){
// TODO: Add your command handler code here
m_drawstyle=BRESENHAM_LINE;
Invalidate(true);
}
int CcgdemoView::BresenhamLine(CDC* pDC, int x0,int y0,int x1, int y1,int color)
{
//竖线(为避免k=inf)
if(x0==x1)
{
if(y0<=y1)
for(int y=y0;y<=y1;y++) pDC->SetPixel(x0,y,color);
else
for(int y=y0;y>=y1;y--) pDC->SetPixel(x0,y,color);
return 0;
}
//横线(仅为提高效率)
if(y0==y1)
{
if(x0<=x1)
for(int x=x0;x<=x1;x++) pDC->SetPixel(x,y0,color);
else
for(int x=x0;x>=x1;x--) pDC->SetPixel(x,y0,color);
return 0;
}
//其他情况 共分两大类:x0<x1和x0>x1。每一类下分四种情况:k<-1, -1<k<0, 0<k<1, k>1,共八种情况。
pDC->SetPixel(x0,y0,color);
int x,y,dx,dy,temp,e;
if(x0==x1&&y0==y1)return 0;
dx=x1-x0;dy=y1-y0;
x=x0;y=y0;
if(x0>x1)
{
if(dy>0) //k<0
{
if(dy<abs(dx)) //-1<k<0
{
dx=-dx;dy=-dy;x=x1;y=y1;
e=-dx;
for(temp=0;temp<dx;temp++,x++)
{
pDC->SetPixel(x,y,color);
e=e-2*dy;
if(e>=0)
{
y--;
e=e-2*dx;
}
}
}
else if(dy>abs(dx)) // k<-1
{
e=-dy;
for(temp=0;temp<dy;temp++,y++)
{
pDC->SetPixel(x,y,color);
e=e-2*dx;
if(e>=0)
{
x--;
e=e-2*dy;
}
}
}
}
else if(dy<0) // k>0
{
if(abs(dy)<abs(dx)) // 0<k<1
{
dx=-dx;dy=-dy;x=x1;y=y1;
e=-dx;
for(temp=0;temp<dx;temp++,x++)
{
pDC->SetPixel(x,y,color);
e=e+2*dy;
if(e>=0)
{
y++;
e=e-2*dx;
}
}
}
if(abs(dy)>abs(dx)) // k>1
{
dx=-dx;dy=-dy;x=x1;y=y1;
e=-dy;
for(temp=0;temp<abs(dy);temp++,y++)
{
pDC->SetPixel(x,y,color);
e=e+2*dx;
if(e>=0)
{
x++;
e=e-2*dy;
}
}
}
}
}
if(x0<x1)
{
if(dy<0) //k<0
{
if(abs(dy)<dx) // -1<k<0
{
e=-dx;
for(temp=0;temp<dx;temp++,x++)
{
pDC->SetPixel(x,y,color);
e=e-2*dy;
if(e>=0)
{
y--;
e=e-2*dx;
}
}
}
if(abs(dy)>dx) // k<-1
{
dx=-dx;dy=-dy;x=x1;y=y1;
e=-dy;
for(temp=0;temp<abs(dy);temp++,y++)
{
pDC->SetPixel(x,y,color);
e=e-2*dx;
if(e>=0)
{
x--;
e=e-2*dy;
}
}
}
}
if(dy>0) //k>0
{
if(dy>dx) //k>1
{
e=-dy;
for(temp=0;temp<dy;temp++,y++)
{
pDC->SetPixel(x,y,color);
e=e+2*dx;
if(e>=0)
{
x++;
e=e-2*dy;
}
}
}
if(dy<dx) // 0<k<1
{
e=-dx;
for(temp=0;temp<dx;temp++,x++)
{
pDC->SetPixel(x,y,color);
e=e+2*dy;
if(e>=0)
{
y++;
e=e-2*dx;
}
}
}
}
}
}