采用 MFC 编制 MVC 模式之球体演示程序
2006-07-19 11:30:56 来源:WEB开发网核心提示: void CGraphicView::OnPaint(){... .....if(!bPaintSphere)dc.DrawText("球体演示",rect,DT_VCENTER|DT_CENTER|DT_SINGLELINE);else{ int r=(int)m_r
void CGraphicView::OnPaint()
{
... .....
if(!bPaintSphere)
dc.DrawText("球体演示",rect,DT_VCENTER|DT_CENTER|DT_SINGLELINE);
else
{
int r=(int)m_radius;//半径取整
CPoint MiddlePoint = rect.CenterPoint();//以矩形框的中心为球心
int x=MiddlePoint.x;
int y=MiddlePoint.y;
oldpen = (CPen*)dc.SelectObject(&solid_pen);
oldbru = (CBrush*)dc.SelectObject(&brush);
dc.Ellipse(x-r,y-r,x+r,y+r); //先画一个圆形
dc.SelectObject(&dash_pen);
dc.Arc(x-r/2,y-r,x+r/2,y+r,x,y-r,x,y+r); //再画4个半圆弧
dc.Arc(x-r/2,y-r,x+r/2,y+r,x,y+r,x,y-r);
dc.Arc(x-r,y-r/2,x+r,y+r/2,x-r,y,x+r,y);
dc.Arc(x-r,y-r/2,x+r,y+r/2,x+r,y,x-r,y);
... ...
}
}
关于控制器CMVCSphereDlg响应用户输入半径回车核心代码如下:
BOOL CMVCSphereDlg::PreTranslateMessage(MSG* pMsg)
{
UpdateData();
//violation examination
if(m_r<0.||m_r>100)
{
AfxMessageBox("半径输入范围(0---100)");
return false;
}
if(pMsg->message == WM_KEYDOWN)
if(pMsg->wParam == VK_RETURN)//回车
{
CRect rect;
m_GraphicView.GetClientRect(rect);
m_Sphere.SetRadius(m_r);//把用户输入转换成对Model的操作
m_Sphere.UpdateTextView();//更新View
m_Sphere.UpdateGraphicView(m_GraphicView.GetSafeHwnd(),rect,true);//更新View
return true;
}
... ...
}
响应鼠标拖动核心代码如下:
void CMVCSphereDlg::OnMouseMove(UINT nFlags, CPoint point)
{
CRect rect;
m_GraphicView.GetClientRect(rect);
CPoint middlepoint = rect.CenterPoint();
//if click on the graphic view
if(rect.PtInRect(point)&&bIsDragging)
{
double dbDistance2 = (point.x-middlepoint.x)*(point.x-middlepoint.x)+(point.y-middlepoint.y)*(point.y-middlepoint.y);
double dbDistance = sqrt(dbDistance2);
if(dbDistance>100.)
dbDistance = 100.;
m_r = (float)dbDistance;
//update radius edit
UpdateData(false);
m_Sphere.SetRadius(m_r);
m_Sphere.UpdateTextView();
m_Sphere.UpdateGraphicView(m_GraphicView.GetSafeHwnd(),rect,true);
}
... ...
}
该程序功能简单,只是示例性说明采用 MFC 如何实现MVC模型,就当抛砖引玉了。具体实现参考源代码例子。
更多精彩
赞助商链接