在MainDlg.cpp中的OnPaint()函数中的else后添加如下代码:
{
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);
CDC dcMem;
dcMem.CreateCompatibleDC(&dc);
CString strPath = _T(".\\res\\background.png");
CImage backImg;
backImg.Load(strPath);
if(backImg.IsNull())
return;
CBitmap imgBackground;
imgBackground.Attach(backImg.Detach());
BITMAP bitmap;
imgBackground.GetBitmap(&bitmap);
// CBitmap *pOldBmp=dcMem.SelectObject(&imgBackground);
dcMem.SelectObject(&imgBackground);
dc.StretchBlt(0,0,rect.Width(),rect.Height(),&dcMem,0,0,bitmap.bmWidth,
bitmap.bmHeight,SRCCOPY);
CDialogEx::OnPaint();
}
在其他Dlg.cpp中的OnEraseBkgnd()函数中添加如下代码(自适应窗口):
BOOL CDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CRect rect;
GetClientRect(&rect);
CString strPath = _T(".\\res\\bagd.jpg");
CImage backImg;
backImg.Load(strPath);
if (backImg.IsNull())
return 0;
CBitmap bitmap;
bitmap.Attach(backImg.Detach());
CDC memDC;
BITMAP bmp;
memDC.CreateCompatibleDC(pDC);
memDC.SelectObject(&bitmap);
bitmap.GetBitmap(&bmp);
pDC->SetStretchBltMode(COLORONCOLOR); // 防失真
pDC->StretchBlt(rect.left, rect.top, rect.Width(), rect.Height(), &memDC,
0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY);
return 1;
}
若要使得图像跟随背景尺寸变化,可以在OnInitDialog()函数中设置:
CWnd::SetWindowPos(NULL,0,0,GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN),SWP_NOZORDER | SWP_NOMOVE);