#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);
}
}
}