动态改变Picture控件上的位图
DrawPicture(int nBmpResource)
{
CDC dcmem;
CClientDC dc(this);
dcmem.CreateCompatibleDC(&dc);
CBitmap m_Bitmap;
m_Bitmap.LoadBitmap(nBmpResource);
dcmem.SelectObject(m_Bitmap);
CRect rect;
GetDlgItem(IDC_STATIC_Pic)->GetWindowRect(&rect);
ScreenToClient(&rect);
dc.BitBlt(rect.left,rect.top,rect.right,rect.bottom,&dcmem,0,0,SRCCOPY);
}
单击按钮事件
{
m_nBmpResource = IDB_BMP1;//m_nBmpResource 类的成员函数,BMP资源的ID
Invalidate();
}
由于Invalidate(),系统调用对话框的OnPaint()函数
{
CPaintDC dc(this); //一定要有这一句
this->DrawPicture(m_nBmpResource);
CDialog::OnPaint();
}
使用文件中的位图(没有添加到资源中)
void CXXXDlg::DrawPicture(LPCTSTR picture,int width,int height)
{
PAINTSTRUCT ps;
HDC hdc;
HDC hdcmem;
HBITMAP hBm;
BITMAP bm;
//加载位图
//hBm = (HBITMAP)LoadImage(NULL,picture,IMAGE_BITMAP,width,height,LR_LOADFROMFILE);
//获得位图尺寸
GetObject(hBm,sizeof(BITMAP),(LPVOID)&bm);
//获取设备环境
HWND hwnd;
hwnd=this->GetDlgItem(IDC_STATIC_Pic)->GetSafeHwnd();
hdc=::GetDC(hwnd);
//获取设备内存环境
hdcmem=CreateCompatibleDC(hdc);
//释放设备环境
::ReleaseDC(hwnd,hdc);
hdc=::BeginPaint(hwnd,&ps);
//将位图选入内存设备环境
SelectObject(hdcmem,hBm);
//调用函数BitBlt将内存设备环境的位图拷贝到设备环境中
BitBlt(hdc,0,0,bm.bmWidth,bm.bmHeight,hdcmem,0,0,SRCCOPY);
//释放设备环境句柄
::EndPaint(hwnd,&ps);
DeleteObject(hBm);
DeleteDC(hdcmem);
}