MFC 鼠标拖动画圆

先计算出圆心, 半径, 然后再根据圆心半径计算出矩形(正方形)的左上角跟右下角的顶点, 然后用Ellipse函数画圆。


源代码如下:
** view类头文件里添加如下变量
private :
    
bool  m_bLButtonDown;
       bool  m_bErase;
    CPen *  pGrayPen;
    CPen *  pLinePen;
    CPoint old_center;
    CPoint m_pStart;
     int  nRadius;


**View类构造函数添加如下初始化代码:
    pGrayPen  =   new  CPen( 0 1 , RGB( 100 100 100 ));
   
    pLinePen 
=   new  CPen( 0 1 , RGB( 250 0 0 ));


** View类为鼠标添加如下消息响应函数; 按下左键,  按下左键鼠标移动, 释放左键

//  CmfcTestView 消息处理程序

void  CmfcTestView::OnLButtonDown(UINT nFlags, CPoint point)
{
    
// TODO: 在此添加消息处理程序代码和/或调用默认值

    m_bLButtonDown 
= TRUE; // 设左鼠标键按下为真
    m_pStart  = point;
    SetCapture(); 
// 设置鼠标捕获
    CView::OnLButtonDown(nFlags, point);
}


void  CmfcTestView::OnMouseMove(UINT nFlags, CPoint point)
{
    
// TODO: 在此添加消息处理程序代码和/或调用默认值
    if(m_bLButtonDown==TRUE) {

        CDC
* pDC = GetDC(); // 获取设备上下文        
        pDC->SelectObject(pGrayPen); // 选取灰色笔
        pDC->SelectStockObject(NULL_BRUSH);
        pDC
->SetROP2(R2_XORPEN); // 设置为异或绘图方式
        if (m_bErase) // need to erase
            pDC->Ellipse(old_center.x-nRadius, old_center.y-nRadius,
            old_center.x
+nRadius, old_center.y+nRadius);
        }


        
else // 需要擦除为假
            m_bErase = TRUE; // 设需要擦除为真
        CPoint center;
        center.x
=(float(m_pStart.x+point.x))/2;
        center.y
=(float(m_pStart.y+point.y))/2;
        nRadius
=sqrt((double)(point.y-m_pStart.y)*(point.y-m_pStart.y)+
        (point.x
-m_pStart.x)*(point.x-m_pStart.x))/2;
        pDC
->Ellipse(center.x-nRadius, center.y-nRadius, 
            center.x
+nRadius, center.y+nRadius);
        old_center
=center;
        ReleaseDC(pDC); 
// 释放设备上下文
    }

    CView::OnMouseMove(nFlags, point);

}


void  CmfcTestView::OnLButtonUp(UINT nFlags, CPoint point)
{
    
// TODO: 在此添加消息处理程序代码和/或调用默认值
    ReleaseCapture();
    
if (m_bLButtonDown) {
        CDC
* pDC = GetDC(); // 获取设备上下文
        pDC->SelectStockObject(NULL_BRUSH);
        pDC
->SelectObject(pLinePen); // 选择笔
        pDC->SetROP2(R2_COPYPEN); // 设置为覆盖绘图方式
        CPoint center; // 圆心
        
//calculate the center
        center.x=(float(m_pStart.x+point.x))/2;
        center.y
=(float(m_pStart.y+point.y))/2;
        
// nRadius is a class member, double
        nRadius=sqrt(double(point.y-m_pStart.y)*(point.y-m_pStart.y)+
        (point.x
-m_pStart.x)*(point.x-m_pStart.x))/2;
        pDC
->Ellipse(center.x-nRadius, center.y-nRadius, center.x+nRadius, center.y+nRadius);
        ReleaseDC(pDC); 
// 释放设备上下文
        m_bLButtonDown = FALSE; // 重设左鼠标键按下为假
        m_bErase = FALSE; // 重需要擦除为假
    }

    CView::OnLButtonUp(nFlags, point);
}



你可能感兴趣的:(null,mfc,float)