先計算出圓心, 半徑, 然後再根據圓心半徑計算出矩形(正方形)的左上方跟右下角的頂點, 然後用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);
}