1. 程式人生 > >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。