C++基于MFC的对话框鼠标拖动和放缩,已经加载到picture控件的图片
时间: 2024-02-28 17:53:38 浏览: 105
以下是基于MFC的对话框实现鼠标拖动和放缩已经加载到picture控件的图片的代码:
首先,您需要在对话框的资源视图中添加一个Picture控件,然后在代码中关联控件并加载一张图片。
```c++
// 声明控件变量
CStatic m_picCtrl;
BOOL CMyDialog::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 关联控件
m_picCtrl = (CStatic*)GetDlgItem(IDC_PIC_CTRL);
// 加载图片
CImage image;
image.Load(_T("test.jpg"));
m_picCtrl.SetBitmap(image.Detach());
return TRUE;
}
```
接下来,您需要在对话框类中添加变量和函数,用于保存和处理鼠标拖动和放缩的相关信息。
```c++
// 声明变量
BOOL m_bDragging;
CPoint m_ptLast;
int m_nScalePercent;
// 声明函数
void DragPictureCtrl(CPoint pt);
void ScalePictureCtrl(int nScalePercent);
```
然后,在对话框类的消息映射中添加对应的消息处理函数。
```c++
BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_MOUSEWHEEL()
END_MESSAGE_MAP()
```
```c++
void CMyDialog::OnLButtonDown(UINT nFlags, CPoint point)
{
m_bDragging = TRUE;
m_ptLast = point;
CDialogEx::OnLButtonDown(nFlags, point);
}
void CMyDialog::OnLButtonUp(UINT nFlags, CPoint point)
{
m_bDragging = FALSE;
CDialogEx::OnLButtonUp(nFlags, point);
}
void CMyDialog::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bDragging)
{
DragPictureCtrl(point);
}
CDialogEx::OnMouseMove(nFlags, point);
}
BOOL CMyDialog::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
if (zDelta > 0 && m_nScalePercent < 500)
{
m_nScalePercent += 10;
}
else if (zDelta < 0 && m_nScalePercent > 10)
{
m_nScalePercent -= 10;
}
ScalePictureCtrl(m_nScalePercent);
return CDialogEx::OnMouseWheel(nFlags, zDelta, pt);
}
```
最后,实现处理函数。
```c++
void CMyDialog::DragPictureCtrl(CPoint pt)
{
CRect rc;
m_picCtrl.GetClientRect(&rc);
int dx = pt.x - m_ptLast.x;
int dy = pt.y - m_ptLast.y;
rc.OffsetRect(dx, dy);
m_picCtrl.MoveWindow(&rc);
m_ptLast = pt;
}
void CMyDialog::ScalePictureCtrl(int nScalePercent)
{
CImage image;
image.Load(_T("test.jpg"));
int width = (int)(image.GetWidth() * nScalePercent / 100.0f);
int height = (int)(image.GetHeight() * nScalePercent / 100.0f);
CBitmap bitmap;
bitmap.CreateBitmap(width, height, image.GetBPP(), 1, NULL);
CDC* pDC = m_picCtrl.GetDC();
CDC memDC;
memDC.CreateCompatibleDC(pDC);
CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);
memDC.SetStretchBltMode(COLORONCOLOR);
image.StretchBlt(memDC.GetSafeHdc(), 0, 0, width, height, SRCCOPY);
memDC.SelectObject(pOldBitmap);
m_picCtrl.SetBitmap(bitmap.Detach());
m_nScalePercent = nScalePercent;
}
```
这样,您就可以在MFC的对话框中实现鼠标拖动和放缩已经加载到picture控件的图片了。注意,以上代码仅供参考,具体实现可能需要根据您的实际需求进行调整。
阅读全文