MFC双缓冲绘图实现在对话框中的picture控件上绘图(包含随鼠标中轴变化改变图形大小)
1、新建MFC对话框项目
2、新建完成后,将页面切换到资源视图,从工具箱中拖出Picture Control控件到对话框,并调整大小,然后拖动一个Button控件如下图中Test按钮。
3、添加Test这个Button对应的按键响应事件,开始写代码
/*定义vecPoint存开始的点数据,vec存鼠标中轴移动后点的数据,percent存当前图形变化的比率*/
vector vecPoint;
vector vec;
static double percent = 1.0;
//test代码
void CMFCDrawDlg::OnBnClickedButtonTest()
{
CString str;
str.Format(_T("Percent:1.0"));
GetDlgItem(IDC_PERCENT)->SetWindowText(str);
percent =1.0;
POINT pointTest1;
pointTest1.x = -100;
pointTest1.y = -100;
POINT pointTest2;
pointTest2.x = 100;
pointTest2.y = 100;
if( vecPoint.size()==0 )
{
vecPoint.push_back(pointTest1);
vecPoint.push_back(pointTest2);
}
DrawToPicture( vecPoint );
}
//鼠标中轴滚动事件的响应函数
BOOL CMFCDrawDlg::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
if( vec.size() == 0 )
{
vec = vecPoint;
}
if( zDelta == 120 )
{
for( int i=0;i < vec.size();i++)
{
vec[i].x = vec[i].x / 1.1;
vec[i].y = vec[i].y / 1.1;
}
percent /=1.1;
}
else if( zDelta == -120 )
{
for( int i=0;i < vec.size();i++)
{
vec[i].x = vec[i].x * 1.1;
vec[i].y = vec[i].y * 1.1;
}
percent *=1.1;
}
CString str;
str.Format(_T("Percent:%lf"),percent);
GetDlgItem(IDC_PERCENT)->SetWindowText(str);
DrawToPicture(vec);
return CDialogEx::OnMouseWheel(nFlags, zDelta, pt);
}
//图形绘制到picture控件上的处理,使用双缓冲绘图
void CMFCDrawDlg::DrawToPicture(vector &vec)
{
if( vec.size() != 2 )
{
return;
}
//获取出piture控件的句柄
CWnd *pWnd = GetDlgItem(IDC_CTRL_PICTURE);
CDC *pDC = pWnd->GetDC();
CRect picRect ;
pWnd->GetClientRect(picRect);
pWnd->Invalidate();
pWnd->UpdateWindow();
CDC MemDC;
CBitmap MemBitmap;
if( NULL == MemDC.CreateCompatibleDC(pDC) )
{
return;
}
if( NULL == MemBitmap.CreateCompatibleBitmap(pDC, picRect.Width(), picRect.Height()))
{
return ;
}
CBitmap *pOldBit = MemDC.SelectObject(&MemBitmap);
MemDC.FillSolidRect(0, 0, picRect.Width(), picRect.Height(), RGB(255,255,255));
CBrush fillbrush;
CBrush *oldbrush;
fillbrush.CreateSolidBrush(RGB(255,0,0));
oldbrush=MemDC.SelectObject(&fillbrush);
//辅助线 仅做参考使用
POINT test;
test.x = 0;
test.y = picRect.CenterPoint().y;
MemDC.MoveTo(test);
test.x = picRect.right;
test.y = picRect.CenterPoint().y;
MemDC.LineTo(test);
test.x = picRect.CenterPoint().x;
test.y = 0;
MemDC.MoveTo(test);
test.x = picRect.CenterPoint().x;
test.y = picRect.bottom;
MemDC.LineTo(test);
MemDC.Rectangle(vec[0].x +picRect.CenterPoint().x ,vec[0].y + picRect.CenterPoint().y ,vec[1].x + picRect.CenterPoint().x,vec[1].y + picRect.CenterPoint().y);
// 将内存中的图拷贝到屏幕上进行显示,绘图完成后清理
pDC->BitBlt(0, 0, picRect.Width(), picRect.Height(), &MemDC, 0, 0, SRCCOPY);
MemDC.SelectObject(pOldBit);
//使用GetDC()要用ReleaseDC
::ReleaseDC(this->m_hWnd, MemDC);
MemDC.SelectObject(oldbrush);
fillbrush.DeleteObject();
MemBitmap.DeleteObject();
}
以下是我的个人公众号,主要作为C/C++语言技术分享使用,该公众号里干货满满,如果您有对此博文的疑问或者java方面的问题也可以添加公众号交流讨论。最后,再次希望您能添加关注,互相交流互相学习共同进步:
完整代码:
https://download.csdn.net/download/coding13/10458148