这个工程在上个博客VC++ game开场篇中的基础上继续写:
显示位图做以下几个工作:
1:定义一个CDC* cDC 指针,定义方法可以手动到.h中定义,也可以在类视图下,右键你要添加变量的类,选择添加变量,选择变量类型,作用范围,变量名。一些没有罗列出来的数据类型,可以手动输入:比如:RECT CBitmap等等。
我们定义一个CDC指针和一个CBimap 指针
2:在资源文件中将其初始化。并为bitmap加载资源。详情见代码。
3:在类视图中对选择的类进行添加VM_ONPAINT消息,在自动生成的代码中进行如下操作,详情见代码:
CMyWnd.cpp:
// MyWnd.cpp : 实现文件
//
#include "stdafx.h"
#include "MyWnd.h"
// CMyWnd
IMPLEMENT_DYNCREATE(CMyWnd, CFrameWnd)
CMyWnd::CMyWnd()
: cDc(NULL)
{
Create(NULL,"window");
CClientDC dc(this);
/*
beside CClientDc ,there are another two CDC'child class:
CWindowDC(draw everywhere you want )
CPaintDC(only in OnPaint()function)
*/
//GetClientRect(windowRect);//the show view
//GetWindowRect(windowRect); the whole view
//dc.TextOutA(100,100,"GOOD",5); have a problem
int width=dc.GetDeviceCaps(HORZRES);//get the decice's width
int height=dc.GetDeviceCaps(VERTRES);
width=(width-800)/2;
height=(height-600)/2;
MoveWindow(width,height,800,600);
cDc=new CDC();
bacBitmap=new CBitmap();
bacBitmap->m_hObject=(HBITMAP)::LoadImage(NULL,"bac.bmp",IMAGE_BITMAP,800,520,LR_LOADFROMFILE);
}
CMyWnd::~CMyWnd()
{
}
BEGIN_MESSAGE_MAP(CMyWnd, CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
// CMyWnd 消息处理程序
void CMyWnd::OnPaint()
{ /*
steps to show a bitmap
1:new a CDC pointer
2:a CBitmap Object and load the bitmap resource
3:at the OnPaint()function CDC pointer CreateCompatibleDC(&dc);
4:CDC pointer select the bitmap object
5:CPaintDC invoke BitBit()function
*/
CPaintDC dc(this); // device context for painting
cDc->CreateCompatibleDC(&dc);
cDc->SelectObject(bacBitmap);
dc.BitBlt(0,0,800,520,cDc,0,0,SRCCOPY);
// TODO: 在此处添加消息处理程序代码
// 不为绘图消息调用 CFrameWnd::OnPaint()
}