#pragma once
#include "atlimage.h"
class CImageDraw
{
public:
CImageDraw(void);
public:
~CImageDraw(void);
public:
static bool LoadImageFromResource(IN CImage* pImage,IN UINT nResID,
IN LPCTSTR lpTyp);
void TileDraw(CDC *pDC,CImage &img,LPRECT pRect);
};
#include "StdAfx.h"
#include "ImageDraw.h"
CImageDraw::CImageDraw(void)
{
}
CImageDraw::~CImageDraw(void)
{
}
bool CImageDraw::LoadImageFromResource(IN CImage* pImage,IN UINT nResID,
IN 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);//the return value is a pointer to the first byte of the resource
LPSTREAM pStream = NULL;
DWORD dwSize = ::SizeofResource(AfxGetResourceHandle(), hRsrc);//The number of bytes in the resource
HGLOBAL hNew = ::GlobalAlloc(GHND, dwSize);//該函數從堆中分配一定數目的位元組數,GHND 標識 為GMEM_MOVEABLE 和 GMEM_ZEROINIT的組合. 傳回值是新分配的堆的控制代碼
LPBYTE lpByte = (LPBYTE)::GlobalLock(hNew);//鎖定記憶體中指定的記憶體塊,並返回一個地址值,令其指向記憶體塊的起始處。除非用 GlobalUnlock 函數將記憶體塊解鎖,否則地址會一直保持有效
::memcpy(lpByte, lpVoid, dwSize);//複製資源
// 解除記憶體中的指定資源
::GlobalUnlock(hNew);
// 從指定記憶體建立流對象
HRESULT ht = ::CreateStreamOnHGlobal(hNew, TRUE, &pStream);//函數從指定記憶體建立流對象,TRU表示hGlobal最終會自動釋放
if ( ht != S_OK )
{
GlobalFree(hNew);
}
else
{
// 載入圖片
pImage->Load(pStream);
GlobalFree(hNew);
}
// 釋放資源
::FreeResource(hImgData);
return true;
}
void CImageDraw::TileDraw(CDC *pDC,CImage &img,LPRECT pRect)
{
int x,y,w,h;
w=img.GetWidth();
h=img.GetHeight();
for (y=pRect->top;y<pRect->bottom-h;y+=h)
{
for (x=pRect->left;x<pRect->right-w;x+=w)
{
img.Draw(pDC->GetSafeHdc(),x,y);
}
if (x!=pRect->right)
{
img.Draw(pDC->GetSafeHdc(),x,y,pRect->right-x,h
,0,0,pRect->right-x,h);
}
}
if (y!=pRect->bottom)
{
for (x=pRect->left;x<pRect->right-w;x+=w)
{
img.Draw(pDC->GetSafeHdc(),x,y,w,pRect->bottom-y
,0,0,w,pRect->bottom-y);
}
if (x!=pRect->right)
{
img.Draw(pDC->GetSafeHdc(),x,y
,pRect->right-x,pRect->bottom-y
,0,0
,pRect->right-x,pRect->bottom-y);
}
}
}