//-----------pnglib.h#include "stdafx.h"#include "afxdialogex.h"#include "atlimage.h"class DrawImage{public: DrawImage(UINT, LPCTSTR); DrawImage(HWND, UINT, LPCTSTR); ~DrawImage();public: void Draw(int, int, int, int); void Destroy(); BOOL LoadPNG(UINT, LPCTSTR); BOOL LoadPNG(HWND, UINT, LPCTSTR); int GetWidth(); int GetHeight();private: BOOL Load_Resource(CImage *, UINT, LPCTSTR); CImage img; HDC hDC; HWND hWnd;};
//----------------pnglib.cpp#include "stdafx.h"#include "pnglib.h"DrawImage::DrawImage(UINT nResID, LPCTSTR lpTyp){ LoadPNG(nResID, lpTyp);}DrawImage::DrawImage(HWND hWndin, UINT nResID, LPCTSTR lpTyp){ LoadPNG(hWndin, nResID, lpTyp);}DrawImage::~DrawImage(){ Destroy();}int DrawImage::GetWidth(){ return img.GetWidth();}int DrawImage::GetHeight(){ return img.GetHeight();}void DrawImage::Draw(int xDest, int yDest, int WidthDest, int HeightDest){ img.Draw(hDC, xDest, yDest, WidthDest, HeightDest);}void DrawImage::Destroy(){ img.Destroy(); ReleaseDC(hWnd, hDC);}BOOL DrawImage::LoadPNG(UINT nResID, LPCTSTR lpTyp){ hDC = ::GetDC(hWnd); return Load_Resource(&img, nResID, lpTyp);}BOOL DrawImage::LoadPNG(HWND hWndin, UINT nResID, LPCTSTR lpTyp){ hWnd = hWndin; hDC = ::GetDC(hWnd); return Load_Resource(&img, nResID, lpTyp);}BOOL DrawImage::Load_Resource(CImage *pImage, UINT nResID, LPCTSTR lpTyp){ if (pImage == NULL) { return false; } pImage->Destroy(); HRSRC hRsrc = ::FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(nResID), lpTyp); if (hRsrc == NULL)return false; HGLOBAL hImgData = ::LoadResource(AfxGetResourceHandle(), hRsrc); if (hImgData == NULL) { ::FreeResource(hImgData); return false; } LPVOID lpVoid = ::LockResource(hImgData); LPSTREAM pStream = NULL; DWORD dwSize = ::SizeofResource(AfxGetResourceHandle(), hRsrc); HGLOBAL hNew = ::GlobalAlloc(GHND, dwSize); LPBYTE lpByte = (LPBYTE)::GlobalLock(hNew); ::memcpy(lpByte, lpVoid, dwSize); ::GlobalUnlock(hNew); HRESULT ht = ::CreateStreamOnHGlobal(hNew, TRUE, &pStream); if (ht != S_OK) { GlobalFree(hNew); } else { pImage->Load(pStream); GlobalFree(hNew); } ::FreeResource(hImgData); for (int i = 0; i < img.GetWidth(); i++) { for (int j = 0; j < img.GetHeight(); j++) { unsigned char* puc = reinterpret_cast(img.GetPixelAddress(i, j)); puc[0] = puc[0] * puc[3] / 255; puc[1] = puc[1] * puc[3] / 255; puc[2] = puc[2] * puc[3] / 255; } } if (img.IsNull()) { return false; } return true;}
用法:
把你的PNG添加到工程里面,修改资源ID为 PIC_PNG1用法1:默认在当前窗口中绘图DrawImage m_png(PIC_PNG1,"png");m_png.Draw(100,100,m_png.GetWidth(),m_png.GetHeight());//其中两个100是图片左上角的坐标用法2:可以在任何窗口中绘图HWND hWndin = 桌面句柄;//在桌面绘图,需要自己去获取DrawImage m_png(hWndin,PIC_PNG1,"png");m_png.Draw(100,100,m_png.GetWidth(),m_png.GetHeight());
作者:天楼桦