MFC绘图的几种方法
/*
1.可以使用OnDraw()函数直接绘图;
2.使用菜单绘图(添加菜单——添加菜单函数(消息映射函数))
3.自定义函数绘图(添加成员函数——可以在OnDraw()函数调用,也可以在菜单函数里调用)
4.工具条设计(实现图标和子菜单关联)
*/
1.可以使用OnDraw()函数直接绘图;
/
// CTestView drawing
void CTestView::OnDraw(CDC* pDC)
{
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
CRect rect;
GetClientRect(&rect);
pDC->SetMapMode(MM_ANISOTROPIC);
pDC->SetWindowExt(rect.Width(),rect.Height());
pDC->SetViewportExt(rect.Width(),-rect.Height());
pDC->SetViewportOrg(rect.Width()/2,rect.Height()/2);
rect.OffsetRect(-rect.Width()/2,-rect.Height()/2);
CPoint ld,rt;//
//绘制外部黑色椭圆
ld=CPoint(-200,-150),rt=CPoint(200,150);
CBrush NewBrush, *pOldBrush;
NewBrush.CreateSolidBrush(RGB(0,0,0));
pOldBrush=pDC->SelectObject(&NewBrush);
pDC->Ellipse(CRect(ld,rt));
pDC->SelectObject(pOldBrush);
NewBrush.DeleteObject();
//绘制白色外部圆
ld=CPoint(-147,-147),rt=CPoint(147,147);
pDC->Ellipse(CRect(ld,rt));
//绘制内部黑色椭圆
ld=CPoint(-140,-90),rt=CPoint(140,90);
NewBrush.CreateSolidBrush(RGB(0,0,0));
pOldBrush=pDC->SelectObject(&NewBrush);
pDC->Ellipse(CRect(ld,rt));
pDC->SelectObject(pOldBrush);
NewBrush.DeleteObject();
//绘制白色内部圆
ld=CPoint(-88,-88),rt=CPoint(88,88);
pDC->Ellipse(CRect(ld,rt));
}
2.使用菜单绘图(添加菜单——添加菜单函数(消息映射函数))
void CTestView::OnMdraw()
{
// TODO: Add your command handler code here
CDC * pDC=GetDC();//初始化指针pDC
/*添加上一种方法的代码*/
ReleaseDC(pDC);//释放指针
}
3.自定义函数绘图
void CTestView::DrawObject(CDC *pDC)
{
CRect rect;
GetClientRect(&rect);
pDC->SetMapMode(MM_ANISOTROPIC);
pDC->SetWindowExt(rect.Width(),rect.Height());
pDC->SetViewportExt(rect.Width(),-rect.Height());
pDC->SetViewportOrg(rect.Width()/2,rect.Height()/2);
rect.OffsetRect(-rect.Width()/2,-rect.Height()/2);
CPoint ld,rt;//
//绘制外部黑色椭圆
ld=CPoint(-200,-150),rt=CPoint(200,150);
CBrush NewBrush, *pOldBrush;
NewBrush.CreateSolidBrush(RGB(0,0,0));
pOldBrush=pDC->SelectObject(&NewBrush);
pDC->Ellipse(CRect(ld,rt));
pDC->SelectObject(pOldBrush);
NewBrush.DeleteObject();
//绘制白色外部圆
ld=CPoint(-147,-147),rt=CPoint(147,147);
pDC->Ellipse(CRect(ld,rt));
//绘制内部黑色椭圆
ld=CPoint(-140,-90),rt=CPoint(140,90);
NewBrush.CreateSolidBrush(RGB(0,0,0));
pOldBrush=pDC->SelectObject(&NewBrush);
pDC->Ellipse(CRect(ld,rt));
pDC->SelectObject(pOldBrush);
NewBrush.DeleteObject();
//绘制白色内部圆
ld=CPoint(-88,-88),rt=CPoint(88,88);
pDC->Ellipse(CRect(ld,rt));
}
两种方式调用
(1)在OnDraw()函数里面调用
// CTestView drawing
void CTestView::OnDraw(CDC* pDC)
{
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
DrawObject(pDC);
}
(2)在菜单函数里面调用
// CTestView message handlers
void CTestView::OnMdraw()
{
// TODO: Add your command handler code here
CDC * pDC=GetDC();//初始化指针pDC
DrawObject(pDC);
ReleaseDC(pDC);//释放指针
}
4.工具条设计(实现图标和子菜单关联)
5、运行结果