在许多画图的程序中,大家可以拖动一个图形.其实,实现这个比较简单.只是不断的重画就可以达到预期的效果.windows是基于消息时间的系统.当我们按下左键时,便激发一个WM_LBUTTONDOWN的消息,移动鼠标时,便激发一个WM_MOUSEMOVE的消息,松开鼠标时,也会激起一个WM_LBUTTONUP的消息.所以,当我们拖动一个图形时,可以在移动鼠标时,记住图形的位置.然后使该区域无效,实现重画.我们现在就实现一个可以拖动的圆形动画.为了更好的记住圆形的位置.我们设置一个类型为CPoint的m_pointLeftTop变量.以记住鼠标左上角的坐标.设置一个类型为CSize的m_sizecircle,用来记住图形的大小.设置一个类型为BOOL的m_bcaptured的变量,用来标识鼠标是否按下.在试图类的构造函数里.初始化这些变量.代码如下:
CMyView::CMyVi ():m_sizeEllipse(100,-100);
m_PointTopLeft(0,0);
m_sizeOffset(0,0)
{
m_bCaptured = FALSE;
}
然后分别添加鼠标消息.WM_LBUTTONDOWN,WM_LBUTTONUP,WM_MOUSEMOVE.首先,在左键按下的鼠标消息里,先判断点击点是否在我们的圆形区域里.如果是,则计算点击点到图形左上角的偏移量.代码如下:
CMyView::OnLButtonDown(UINT nFlags,CPoint point)
{
CRect rectEllipse(m_pointTopLeft,m_sizeEllipse);
CRgn circle;
CClientDC dc(this);
OnPrepareDC(&dc);
dc.LpToDp(rectEllipse);
circle.CreateEllipseRgnIndirect(rectEllipse);
if(circle.PtInRegion(point))
{
SetCapture();
m_bCaptured = TRUE;
CPoint pointTopLeft(m_pointTopLeft);
dc.LpToDp(&pointTopLeft);
m_sizeOffset = point - pointTopLeft;
SetCursor(LoadCursor(NULL,IDC_CROSS));
}
在WM_LBUTTONUP事件中添加如下代码.
CMyView::OnLButtonUp(UINT nFlag,CPoint point)'
{
if(m_Captured)
{
ReleaseCapture();
m_Catpured = TRUE;
}
}
在WM_MOUSEMOVE事件中添加如下代码:
CMYView::OnMouseMove(UINT nFlag,CPoint point)
{
if(m_Captured)
{
CClientDC dc(this);
OnPrepareDC(&dc);
CRect rectOld(m_pointLeftTop,m_sizeEllipse);
InvalidateRect(rectOld,TRUE);
m_pointTopLeft = point - m_sizeOffset;
dc.DpToLp(&m_pointTopLeft);
CRect rectNew(m_pointTopLeft,m_sizeEllipse);
dc.LptoDP(rectnew);
InvalidateRect(rectNew,TRUE);
}
}
最后在OnDraw函数,重新画圆:
pDC->Ellipse(CRect(m_pointTopLeft,m_sizeEllipse));
整个过程基本上实现了.有的地方需要整理点。.
CMyView::CMyVi ():m_sizeEllipse(100,-100);
m_PointTopLeft(0,0);
m_sizeOffset(0,0)
{
m_bCaptured = FALSE;
}
然后分别添加鼠标消息.WM_LBUTTONDOWN,WM_LBUTTONUP,WM_MOUSEMOVE.首先,在左键按下的鼠标消息里,先判断点击点是否在我们的圆形区域里.如果是,则计算点击点到图形左上角的偏移量.代码如下:
CMyView::OnLButtonDown(UINT nFlags,CPoint point)
{
CRect rectEllipse(m_pointTopLeft,m_sizeEllipse);
CRgn circle;
CClientDC dc(this);
OnPrepareDC(&dc);
dc.LpToDp(rectEllipse);
circle.CreateEllipseRgnIndirect(rectEllipse);
if(circle.PtInRegion(point))
{
SetCapture();
m_bCaptured = TRUE;
CPoint pointTopLeft(m_pointTopLeft);
dc.LpToDp(&pointTopLeft);
m_sizeOffset = point - pointTopLeft;
SetCursor(LoadCursor(NULL,IDC_CROSS));
}
在WM_LBUTTONUP事件中添加如下代码.
CMyView::OnLButtonUp(UINT nFlag,CPoint point)'
{
if(m_Captured)
{
ReleaseCapture();
m_Catpured = TRUE;
}
}
在WM_MOUSEMOVE事件中添加如下代码:
CMYView::OnMouseMove(UINT nFlag,CPoint point)
{
if(m_Captured)
{
CClientDC dc(this);
OnPrepareDC(&dc);
CRect rectOld(m_pointLeftTop,m_sizeEllipse);
InvalidateRect(rectOld,TRUE);
m_pointTopLeft = point - m_sizeOffset;
dc.DpToLp(&m_pointTopLeft);
CRect rectNew(m_pointTopLeft,m_sizeEllipse);
dc.LptoDP(rectnew);
InvalidateRect(rectNew,TRUE);
}
}
最后在OnDraw函数,重新画圆:
pDC->Ellipse(CRect(m_pointTopLeft,m_sizeEllipse));
整个过程基本上实现了.有的地方需要整理点。.