加载位图有好多方法,用picture控件也可以
不用控件的话可以:
添加变量IPicture *m_pPicture;
添加两个函数BOOL CCommanpictureDlg::DrawFromFile(CString fileName, CDC *pDC);
HRESULT CCommanpictureDlg::LoadFromBuffer(BYTE *pBuff, int nSize);
说明:这样显示的图片如果图片太大,不能全部显示,除非你对话框也足够大,可以改用Strechblt替换BitBlt函数,感觉还是不方便。
代码如下:
void CCommanpictureDlg::OnPaint()
{
CPaintDC dc(this); // device context for painting
if (IsIconic())
{
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CString filename;
//添加图像路径
filename="ye.bmp";
DrawFromFile(filename,&dc);
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
//
the minimized window.
HCURSOR CCommanpictureDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
HRESULT CCommanpictureDlg::LoadFromBuffer(BYTE *pBuff, int nSize)
{
//定义并初始化返回结果为FALSE
bool bResult=false;
//分配存储空间
HGLOBAL hGlobal=GlobalAlloc(GMEM_MOVEABLE,nSize);
//定义图像数据指针
void* pData=GlobalLock(hGlobal);
//数据复制
memcpy(pData,pBuff,nSize);
//释放内存空间
GlobalUnlock(hGlobal);
//定义数据流指针
IStream* pStream =NULL;
//创建数据流
if(CreateStreamOnHGlobal(hGlobal,TRUE,&pStream)==S_OK)
{
//定义返回结果
HRESULT hr;
//加载图片
if((hr=OleLoadPicture(pStream,nSize,FALSE,IID_IPicture,(LPVOID*)
&m_pPicture))==S_OK)
bResult=true;
//释放数据流
pStream->Release();
}
return bResult;
}
BOOL CCommanpictureDlg::DrawFromFile(CString fileName, CDC *pDC)
{
CFile cFile;
CFileException e;
//打开文件
if(cFile.Open(fileName,CFile::modeRead| CFile::typeBinary,&e))
{
BYTE* pBuff=new BYTE[cFile.GetLength()];
//将文件读入缓存
if(cFile.Read(pBuff,cFile.GetLength())>0)
LoadFromBuffer(pBuff,cFile.GetLength());
//释放缓存
delete [] pBuff;
//定义图像尺寸
long hmWidth;
long hmHeight;
//获取图像尺寸
m_pPicture->get_Width(&hmWidth);
m_pPicture->get_Height(&hmHeight);
int nWidth=MulDiv(hmWidth,pDC->GetDeviceCaps(LOGPIXELSX),2540);
int nHeight=MulDiv(hmHeight,pDC->GetDeviceCaps(LOGPIXELSY),2540);
//在内存中画
CDC MemDC;
CBitmap bmp;
bmp.CreateCompatibleBitmap(pDC,nWidth,nHeight);
MemDC.CreateCompatibleDC(NULL);
MemDC.SelectObject(&bmp);
m_pPicture->Render(MemDC.m_hDC,0,0,nWidth,nHeight,0,hmHeight,hmWidth,-hmHeight,
NULL);
//至此,已经把图像画在内存dc上了,剩下的就是copy到显示dc上了,可以使用BitBlt
//方法直接copy,也可以使用Stretch缩放copy
pDC->BitBlt(0,0,nWidth,nHeight,&MemDC,0,0,SRCCOPY);
}
return false;
}