Bresenham线算法

    技术2022-06-25  43

    void Swap(int *p1,int *p2) { *p1^=*p2; *p2^=*p1; *p1^=*p2; } void Bresenham(CDC *pDC,int x1,int y1,int x2,int y2) { int dx=abs(x2-x1); int dy=abs(y2-y1); if(dx==0&&dy==0) return; //水平线,垂直线,对角线 特殊处理 int inc=0; if(dy==0) { pDC->SetPixel(x1,y1,RGB(0,0,0)); inc=x2>x1?1:-1; while(x1!=x2) { x1+=inc; pDC->SetPixel(x1,y1,RGB(0,0,0)); } return; } if(dx==0) { pDC->SetPixel(x1,y1,RGB(0,0,0)); inc=y2>y1?1:-1; while(y1!=y2) { y1+=inc; pDC->SetPixel(x1,y1,RGB(0,0,0)); } return; } if(dx==dy) { pDC->SetPixel(x1,y1,RGB(0,0,0)); inc=x2>x1?1:-1; int incy=y2>y1?1:-1; while(x1!=x2) { x1+=inc; y1+=incy; pDC->SetPixel(x1,y1,RGB(0,0,0)); } return; } //Bresenham算法 bool bRev=false; if(dy>dx) { Swap(&x1,&y1); Swap(&x2,&y2); Swap(&dx,&dy); bRev=true; } int twoDy=2*dy; int twoDyMinusDx=2*(dy-dx); int p=twoDy-dx; int xi=x2>x1?1:-1; int yi=y2>y1?1:-1; pDC->SetPixel(x1,y1,RGB(0,0,0)); while(x1!=x2) { x1+=xi; if(p>0) { y1+=yi; p+=twoDyMinusDx; } else p+=twoDy; if(bRev) pDC->SetPixel(y1,x1,RGB(0,0,0)); else pDC->SetPixel(x1,y1,RGB(0,0,0)); } }


    最新回复(0)