VC画橡皮筋直线问题
我希望实现“按下鼠标左键后移动鼠标,生成随鼠标位置变化的直线,而松开鼠标左键后,直线不再变化。”的功能。相关代码如下:
void CDrawView::OnLButtonDown(UINT nFlags, CPoint point)
{
m_ptNow = point;
m_ptOrigin = point;
CView::OnLButtonDown(nFlags, point);
}
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
CDC *pDC=GetDC();
Line(point,pDC);
CView::OnLButtonUp(nFlags, point);
}
void CDrawView::OnMouseMove(UINT nFlags, CPoint point)
{
CDC *pDC=GetDC();
Line(point,pDC);
pDC->SetROP2 (R2_NOTXORPEN);
Line(m_ptNow,pDC);
m_ptNow = point;
CView::OnMouseMove(nFlags, point);
}
void CDrawView::Line(CPoint point,CDC* ptr_DC)//用布莱森汉姆算法实现
{
int x,y;
if(m_ptOrigin.x == point.x)
{
if(m_ptOrigin.y <= point.y)
for(y = m_ptOrigin.y ;y <= point.y ; y++)
ptr_DC->SetPixel(m_ptOrigin.x,y,m_clr);
else
for(y = point.y ; y <= m_ptOrigin.y ; y++)
ptr_DC->SetPixel (m_ptOrigin.x,y,m_clr);
}
if(m_ptOrigin.y == point.y)
{
if(m_ptOrigin.x <= point.x)
for(x = m_ptOrigin.x ; x <= point.x ; x++)
ptr_DC->SetPixel(x,m_ptOrigin.y ,m_clr);
else
for(x = point.x ; x <= m_ptOrigin.x ; x++)
ptr_DC->SetPixel (x,m_ptOrigin.y,m_clr);
}
double k = (point.y - m_ptOrigin.y)*1.0/(point.x - m_ptOrigin.x);//斜率
double p = 2*k-1;//布莱森汉姆算法中的中间量 p
if(k > 0 && k <= 1)//斜率为0到1
{
if(x <= point.x)
{
while(x <= point.x)
{
ptr_DC->SetPixel(x,y,m_clr);
if(p>0)
{
y += 1;
x ++;
p += 2*k-2;
}
else
{
y = y;
x ++;
p += 2*k;
}
}
}
if(x > point.x)
{
while(x > point.x)
{
ptr_DC->SetPixel(x,y,m_clr);
if(p>0)
{
y -= 1;
x --;
p -= 2*(k-1);
}
else
{
y = y;
x --;
p -= 2*k;
}
}
}
}
if(k < 0 && k >= -1)//斜率从-1到0
{
if(x <= point.x)
{
while(x <= point.x)
{
ptr_DC->SetPixel (x,y,m_clr);
if(p > 0)
{
y = y;
x ++;
p += 2*k;
}
else
{
y += 1;
x ++;
p += 2*(k-1);
}
}
}
if(x > point.x)
{
while(x > point.x)
{
ptr_DC->SetPixel(x,y,m_clr);
if(p >0)
{
y = y;
x --;
p -= 2*k;
}
else
{
y -= 1;
x --;
p -= 2*(k-1);
}
}
}
}
p = 2.0/k-1;
if(k > 1)
{
if(y <= point.y)
{
while(y <= point.y)
{
ptr_DC->SetPixel (x,y,m_clr);
if(p >= 0)
{
x += 1 ;
y ++;
p += 2.0/k-2;
}
if(p < 0)
{
x = x;
y ++;
p += 2.0/k;
}
}
}
if(y > point.y)
{
while(x > point.x)
{
ptr_DC->SetPixel(x,y,m_clr);
if(p >0)
{
x = x;
y --;
p -= 2.0/k;
}
else
{
x -= 1;
y --;
p -= 2.0/k-2;
}
}
}
}
}
问题描述:我在执行之后,如果鼠标不移入窗口区则正常,一移入,则程序就进入了死循环。用断点调试,发现问题出在Line函数,可是一直没有发现Line函数的错误到底在哪。请各位帮我挑一挑错误,谢谢!