用picture控件显示图片之动态方法(使图片适应于控件大小)
在OnPaint()函数中加入以下代码就ok了,记得准备一副图片jpg的jpeg的都可以,这就是本程序的优点。以后要加载图片,直接copy +Paiste就ok了。
void CPictureDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
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
{
CDialog::OnPaint();
}
//该段程序用于显示图像
//获取picture控件窗口句柄
CWnd *pWnd=GetDlgItem(IDC_PICTURE);
//获取picture控件所在的矩形区域
CRect rect;
pWnd->GetClientRect(&rect);
//获取picture控件的dc
CDC *pDC=pWnd->GetDC();
IStream *pStm;
CFileStatus fstatus;
CFile file;
LONG cb;
//IPicture接口可以显示.jpg格式的图片
IPicture *pPic;
//设置想要显示的图片路径
CString m_sPath="baby.jpg";
//打开图像文件
if(file.Open(m_sPath,CFile::modeRead)&&file.GetStatus(m_sPath,fstatus)
&&((cb=fstatus.m_size)!=-1))
{
//分配全局存储空间
HGLOBAL hGlobal=GlobalAlloc(GMEM_MOVEABLE,cb);
LPVOID pvData=NULL;
if(hGlobal!=NULL)
{
//锁定分配的内存块
if((pvData=GlobalLock(hGlobal))!=NULL)
{
//把文件读入内存缓冲区
file.ReadHuge(pvData,cb);
GlobalUnlock(hGlobal);
CreateStreamOnHGlobal(hGlobal,TRUE,&pStm);
}
}
}
//装载图像文件
if(SUCCEEDED(OleLoadPicture(pStm,fstatus.m_size,TRUE,IID_IPicture,(LPVOID*)&pPic)))
{
OLE_XSIZE_HIMETRIC hmWidth;
OLE_YSIZE_HIMETRIC hmHeight;
//获取图片的真实宽度
pPic->get_Width(&hmWidth);
//获取图片的真实高度
pPic->get_Height(&hmHeight);
//在picture控件上显示图片
pPic->Render(*pDC,0,0,rect.Width(),rect.Height(),0,hmHeight,hmWidth,
-hmHeight,NULL);
pPic->Release();
}
}