2014-08-10 09:18:37|?次阅读|上传:huigezrx【已有?条评论】发表评论
关键词:C/C++, 图形/图像, MFC|来源:唯设编程网
使用VC进行图像处理的时候,CBitmap类为我们提供了丰富的位图处理函数,本文总结了该类的相关函数和常用使用方法,包括加载位图,显示位图,析构CBitmap资源以及在内存中保存位图等内容。
在MFC中,CBitmap类的声明如下:
class CBitmap : public CGdiObject
{
DECLARE_DYNAMIC(CBitmap)
public:
static CBitmap* PASCAL FromHandle(HBITMAP hBitmap);
// Constructors
CBitmap();
BOOL LoadBitmap(LPCTSTR lpszResourceName);
BOOL LoadBitmap(UINT nIDResource);
BOOL LoadOEMBitmap(UINT nIDBitmap); // for OBM_/OCR_/OIC_
#ifndef _AFX_NO_AFXCMN_SUPPORT
BOOL LoadMappedBitmap(UINT nIDBitmap, UINT nFlags = 0,
LPCOLORMAP lpColorMap = NULL, int nMapSize = 0);
#endif
BOOL CreateBitmap(int nWidth, int nHeight, UINT nPlanes, UINT nBitcount,
const void* lpBits);
BOOL CreateBitmapIndirect(LPBITMAP lpBitmap);
BOOL CreateCompatibleBitmap(CDC* pDC, int nWidth, int nHeight);
BOOL CreateDiscardableBitmap(CDC* pDC, int nWidth, int nHeight);
// Attributes
operator HBITMAP() const;
int GetBitmap(BITMAP* pBitMap);
// Operations
DWORD SetBitmapBits(DWORD dwCount, const void* lpBits);
DWORD GetBitmapBits(DWORD dwCount, LPVOID lpBits) const;
CSize SetBitmapDimension(int nWidth, int nHeight);
CSize GetBitmapDimension() const;
// Implementation
public:
virtual ~CBitmap();
#ifdef _DEBUG
virtual void Dump(CDumpContext& dc) const;
#endif
};
不难发现,CBitmap类继承自CGdiObject类,提供了用来加载位图的LoadBitmap函数和其它相关的位图处理函数。下面是CGdiObject类的声明:
class CGdiObject : public CObject
{
DECLARE_DYNCREATE(CGdiObject)
public:
// Attributes
HGDIOBJ m_hObject; // must be first data member
operator HGDIOBJ() const;
HGDIOBJ GetSafeHandle() const;
static CGdiObject* PASCAL FromHandle(HGDIOBJ hObject);
static void PASCAL DeleteTempMap();
BOOL Attach(HGDIOBJ hObject);
HGDIOBJ Detach();
// Constructors
CGdiObject(); // must Create a derived class object
BOOL DeleteObject();
// Operations
#pragma push_macro("GetObject")
#undef GetObject
int _AFX_FUNCNAME(GetObject)(int nCount, LPVOID lpObject) const;
int GetObject(int nCount, LPVOID lpObject) const;
#pragma pop_macro("GetObject")
UINT GetObjectType() const;
BOOL CreateStockObject(int nIndex);
BOOL UnrealizeObject();
BOOL operator==(const CGdiObject& obj) const;
BOOL operator!=(const CGdiObject& obj) const;
// Implementation
public:
virtual ~CGdiObject();
#ifdef _DEBUG
virtual void Dump(CDumpContext& dc) const;
virtual void AssertValid() const;
#endif
};
该类封装了一些更为基础和通用的方法。
下面给出一些CBitmap的使用实例。
// 装载位图 CBitmap bmp; bmp.LoadBitmap(IDB_BITMAP);
装载位图非常简单,直接调用CBitmap类的成员方法LoadBitmap即可,该方法可以实现位图资源文件的加载。
上一部分介绍了从资源文件中加载位图,但是在实际使用中,我们通常需要直接从磁盘文件加载位图文件。为了能让CBitmap能够装载位图文件,必须调用API函数LoadImage,下面是LoadImage函数的原型:
HANDLE LoadImage( HINSTANCE hinst, // handle of the instance containing the image LPCTSTR lpszName, // name or identifier of image UINT uType, // type of image int cxDesired, // desired width int cyDesired, // desired height UINT fuLoad // load flags );
可以通过下面两种方法加载位图文件:
方案1:
HBITMAP hBmp = (HBITMAP)LoadImage(NULL,
m_fileName,
IMAGE_BITMAP,
0, 0,
LR_LOADFROMFILE | LR_DEFAULTCOLOR | LR_DEFAULTSIZE);