mfc中图片控件上加载PNG图片

时间:2024-04-05 11:56:18

MFC加载png资源链接

mfc中图片控件上加载PNG图片

就一个加载png图片的程序弄了一下午,想哭。

***在stadfx.h文件中添加

#include <comdef.h>//初始化一下com口  
#include "gdiplus.h" 
using namespace Gdiplus; 
#pragma comment(lib, "gdiplus.lib") 

1.在app.cpp中添加ULONG_PTR m_gdiplusToken;  

2.在BOOL xxxApp::InitInstance()中添加

GdiplusStartupInput gdiplusStartupInput;  
GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);  

3.在int  xxxApp::ExitInstance()中添加

GdiplusShutdown(m_gdiplusToken);  

4.在app.cpp中添加如下代码:

BOOL ImageFromIDResource(UINT nID, LPCTSTR sTR,Image *&pImg)  
{  
HINSTANCE hInst = AfxGetResourceHandle();  
HRSRC hRsrc = ::FindResource (hInst,MAKEINTRESOURCE(nID),sTR); // type  
if (!hRsrc)  
return FALSE;  
// load resource into memory  
DWORD len = SizeofResource(hInst, hRsrc);  
BYTE* lpRsrc = (BYTE*)LoadResource(hInst, hRsrc);  
if (!lpRsrc)  
return FALSE;  
// Allocate global memory on which to create stream  
HGLOBAL m_hMem = GlobalAlloc(GMEM_FIXED, len);  
BYTE* pmem = (BYTE*)GlobalLock(m_hMem);  
memcpy(pmem,lpRsrc,len);  
GlobalUnlock(m_hMem);  
IStream* pstm;  
CreateStreamOnHGlobal(m_hMem,FALSE,&pstm);  
// load from stream  
pImg=Gdiplus::Image::FromStream(pstm);  
// free/release stuff  
pstm->Release();  
FreeResource(lpRsrc);  
GlobalFree(m_hMem);  
return TRUE;  
}  

5.void CAPP::OnPaint()中添加

CPaintDC dc(this); // device context for painting
//CDC *pDC = this->GetDc();
CClientDC *pDC = new CClientDC(GetDlgItem(IDC_STATIC_PIC));  
CRect rect;  
GetDlgItem(IDC_STATIC_PIC)->GetWindowRect(&rect);  
Graphics graphics(pDC->m_hDC); // Create a GDI+ graphics object  
Image *pimage; // Construct an image  
ImageFromIDResource(IDB_PNG5,_T("PNG"),pimage);  
graphics.DrawImage(pimage, 0, 0,pimage->GetWidth(), pimage->GetHeight());  
delete pDC;  

6.将图片控件属性更改为ower drawer。