MFC 读取 RES 中的 5 张 BMP 图片,计算位图大小并绘制
以下是一个使用 MFC 读取 res 中的 5 张 bmp 图片,并计算位图的宽度和高度,并加载出来画在规定坐标上的示例代码:
// 需要包含的头文件
#include <afxwin.h>
// 定义CMyApp类
class CMyApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
// 定义CMyFrame类
class CMyFrame : public CFrameWnd
{
public:
CMyFrame();
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
};
// 定义CMyApp初始化函数
BOOL CMyApp::InitInstance()
{
m_pMainWnd = new CMyFrame();
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
// 定义CMyFrame构造函数
CMyFrame::CMyFrame()
{
// 加载位图资源
CBitmap bmp1;
bmp1.LoadBitmap(IDB_BITMAP1);
CBitmap bmp2;
bmp2.LoadBitmap(IDB_BITMAP2);
CBitmap bmp3;
bmp3.LoadBitmap(IDB_BITMAP3);
CBitmap bmp4;
bmp4.LoadBitmap(IDB_BITMAP4);
CBitmap bmp5;
bmp5.LoadBitmap(IDB_BITMAP5);
// 计算位图的宽度和高度
BITMAP bmpInfo;
bmp1.GetBitmap(&bmpInfo);
int bmp1Width = bmpInfo.bmWidth;
int bmp1Height = bmpInfo.bmHeight;
bmp2.GetBitmap(&bmpInfo);
int bmp2Width = bmpInfo.bmWidth;
int bmp2Height = bmpInfo.bmHeight;
bmp3.GetBitmap(&bmpInfo);
int bmp3Width = bmpInfo.bmWidth;
int bmp3Height = bmpInfo.bmHeight;
bmp4.GetBitmap(&bmpInfo);
int bmp4Width = bmpInfo.bmWidth;
int bmp4Height = bmpInfo.bmHeight;
bmp5.GetBitmap(&bmpInfo);
int bmp5Width = bmpInfo.bmWidth;
int bmp5Height = bmpInfo.bmHeight;
// 在规定坐标上绘制位图
CDC* pDC = GetDC();
CDC memDC;
memDC.CreateCompatibleDC(pDC);
CBitmap* pOldBitmap;
pOldBitmap = memDC.SelectObject(&bmp1);
pDC->BitBlt(0, 0, bmp1Width, bmp1Height, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
pOldBitmap = memDC.SelectObject(&bmp2);
pDC->BitBlt(bmp1Width, 0, bmp2Width, bmp2Height, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
pOldBitmap = memDC.SelectObject(&bmp3);
pDC->BitBlt(0, bmp1Height, bmp3Width, bmp3Height, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
pOldBitmap = memDC.SelectObject(&bmp4);
pDC->BitBlt(bmp3Width, bmp1Height, bmp4Width, bmp4Height, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
pOldBitmap = memDC.SelectObject(&bmp5);
pDC->BitBlt(0, bmp1Height + bmp3Height, bmp5Width, bmp5Height, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBitmap);
ReleaseDC(pDC);
}
// 定义CMyFrame的消息映射
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
// 定义CMyFrame的绘图函数
void CMyFrame::OnPaint()
{
CPaintDC dc(this);
// 自定义绘图代码
}
// 主函数
CMyApp theApp;
在上述代码中,需要将 IDB_BITMAP1、IDB_BITMAP2、IDB_BITMAP3、IDB_BITMAP4、IDB_BITMAP5 替换为实际的位图资源 ID。
在 CMyFrame 的构造函数中,使用 CBitmap 的 LoadBitmap 函数加载位图资源,然后使用 GetBitmap 函数获取位图的宽度和高度。
然后,创建一个兼容的内存设备上下文(memDC)并选择位图资源,然后使用 BitBlt 函数将位图绘制到指定坐标上。
最后,释放设备上下文的资源。
请注意,在实际应用中,可能需要根据位图的宽度和高度调整绘制的坐标位置,以确保位图不会超出窗口的范围。另外,需要在适当的时候对使用的变量进行回收处理,以避免内存泄漏。
原文地址: https://www.cveoy.top/t/topic/hadk 著作权归作者所有。请勿转载和采集!