CreateCompatibleDC需要Delete吗?

不败的拿破仑 2014-12-06 01:31:26
有些频繁调用的函数里,有类似

CDC memDC;
memDC.CreateCompatibleDC(&dc);
绘图完后,就只执行了
memDC.SelectObjcet(pOldBmp);

但却没有执行任何Delete,或者Release函数。

我的理解是,因为这些函数频繁调用,才这样写的。不知道这样是否有问题呢?
不DeleteDC究竟会有多大影响?
...全文
246 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
不败的拿破仑 2014-12-08
  • 打赏
  • 举报
回复
引用 4 楼 zhllxt 的回复:
看MSDN中关于WIN32 API CreateCompatibleDC的介绍中有一句:When you no longer need the memory DC, call the DeleteDC function. 所以CreateCompatibleDC一定要DeleteDC 但是:你用的是CDC类的CreateCompatibleDC,这个可以不主动调用DeleteDC 的,因为CDC类变量在析构的时候会自动调用DeleteDC
原来如此
zhllxt 2014-12-08
  • 打赏
  • 举报
回复
看MSDN中关于WIN32 API CreateCompatibleDC的介绍中有一句:When you no longer need the memory DC, call the DeleteDC function. 所以CreateCompatibleDC一定要DeleteDC 但是:你用的是CDC类的CreateCompatibleDC,这个可以不主动调用DeleteDC 的,因为CDC类变量在析构的时候会自动调用DeleteDC
dvlinker 2014-12-07
  • 打赏
  • 举报
回复
create出来的gdi对象,都要用delete销毁,否则会导致gdi对象泄漏。在windows下,gdi对象超过1万,程序会出现异常甚至崩溃。
tixisong 2014-12-06
  • 打赏
  • 举报
回复
最好调用它的成员函数DeleteDC(); 楼主可以测试下,搞个while(true) 不断Invalidate,然后打开任务管理器定位到这个进程,查看内存及gdi数量
  • 打赏
  • 举报
回复
In general, do not call this function; the destructor will do it for you. from msdn CDC memDC; 你用的是对象,对象作用域结束后会干嘛?, 指针的话就需要了 GetDc()获取到的dc不能用deleteDc只能用releaseDc
////绘制底面路径imagePath 和 相框路径framePicPath void PaintFramePicture(HDC hDC,RECT rc,CString imagePath,CString framePicPath) { CDC *pDC=new CDC; pDC->Attach(hDC); CString bmpFile; HBITMAP hFgBmp; //画顶层透明位图 CDC DCImage, DCMask; CBitmap Bmp2; //Bmp2.LoadBitmap(IDB_BITMAP2); bmpFile=framePicPath; ///表层框架,相框 hFgBmp = (HBITMAP) LoadImage(NULL,bmpFile,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_DEFAULTSIZE|LR_CREATEDIBSECTION); Bmp2.Attach(hFgBmp); BITMAP bm; Bmp2.GetBitmap(&bm); int nWidth=bm.bmWidth,nHeight=bm.bmHeight; bmpFile=imagePath;//画底层位图//底层内容 CBitmap Bmp1; hFgBmp = (HBITMAP) LoadImage(NULL,bmpFile,IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_DEFAULTSIZE|LR_CREATEDIBSECTION); Bmp1.Attach(hFgBmp); CDC memDC; memDC.CreateCompatibleDC(pDC); memDC.SelectObject(&Bmp1); pDC->BitBlt(0,0,nWidth,nHeight,&memDC,0,0,SRCCOPY); DCImage.CreateCompatibleDC(pDC); DCMask.CreateCompatibleDC(pDC); //把图像装入image DC DCImage.SelectObject(&Bmp2); //为“掩码”位图创建一个单色bitmap CBitmap BmpMask; //把mask位图装入mask DC BmpMask.CreateBitmap(nWidth, nHeight, 1, 1, NULL); //用透明色创建“掩码”位图 DCMask.SelectObject(&BmpMask); //设置透明色 DCImage.SetBkColor(RGB(0,0,0)); DCMask.BitBlt(0, 0, nWidth, nHeight, &DCImage, 0, 0, SRCCOPY); pDC->BitBlt(0,0, nWidth, nHeight, &DCImage, 0, 0, SRCINVERT); pDC->BitBlt(0,0, nWidth, nHeight, &DCMask, 0, 0, SRCAND); pDC->BitBlt(0,0, nWidth, nHeight, &DCImage, 0, 0, SRCINVERT); delete pDC; }
目 录 1. 概述 3 1.1 实训项目简介 3 1.2 实训功能说明 3 1.2.1 基本功能 3 1.2.2 附加功能 3 2. 相关技术 4 2.1 Windows定时器技术 4 2.2 透明贴图实现技术 4 2.3 CObList链表 5 2.4获取矩形区域 6 2.5使用AfxMessageBox显示游戏过程中的提示信息 6 2.6内存释放 6 2.7 CImageList处理爆炸效果 6 2.8对话框的应用 6 3. 总体设计与详细设计 7 3.1 系统模块划分 7 3.2 主要功能模块 8 3.2.1 系统对象类图 8 3.2.2 系统主程序活动图 9 3.2.3 系统部分流程图 9 4. 编码实现 12 4.1 绘制游戏背景位图程序 12 4.2 飞机大战游戏对象的绘制程序 13 4.3 飞机大战游戏对象战机位置的动态控制 15 4.4 飞机大战游戏对象之间的碰撞实现 17 4.5 游戏界面输出当前信息 19 5. 项目程序测试 20 5.1战机移动及子弹发射模块测试 20 5.2 敌机及炸弹模块测试 20 5.3 爆炸模块测试 20 6. 实训中遇到的主要问题及解决方法 21 7. 实训体会 21 1. 概述 1.1 实训项目简介   本次实训项目是做一个飞机大战的游戏,应用MFC编程,完成一个界面简洁流畅、游戏方式简单,玩起来易于上手的桌面游戏。该飞机大战项目运用的主要技术即是MFC编程中的一些函数、链表思想以及贴图技术。 1.2 实训功能说明 1.2.1 基本功能   (1)设置一个战机具有一定的速度,通过键盘,方向键可控制战机的位置,空格键发射子弹。   (2)界面中敌机出现的位置,以及敌机炸弹的发射均为随机的,敌机与敌机炸弹均具有一定的速度,且随着关卡难度的增大,数量和速度均增加。   (3)对于随机产生的敌机和敌机炸弹,若超过矩形区域,则释放该对象。   (4)添加爆炸效果,包括战机子弹打中敌机爆炸、敌机炸弹打中战机爆炸、战机与敌机相撞爆炸以及战机子弹与敌机炸弹相撞爆炸四种爆炸效果。且爆炸发生后敌机、子弹、炸弹均消失,战机生命值减一。 1.2.2 附加功能   (1) 为游戏界面添加了背景图片,并在战机发射子弹、战机击中敌机、敌机击中战机、以及战机敌机相撞时均添加了背景音效。   (2)为游戏设置了不同的关卡,每个关卡难度不同,敌机与敌机炸弹的速度随着关卡增大而加快,进入第二关以后敌机从上下方均会随机出现,且随机发射炸弹。   (3)第一关卡敌机从上方飞出,速度一定,战机每打掉一直敌机则增加一分,每积十分,则为战机增加一个生命值,当战机得分超过50分则可进入下一关;进入第二、三关时敌机速度加快,分别从上下两方飞出,此时战机每得分20、30分,才会增加一个生命值,得分超过100、150分则进入下一关、通关。   (4) 在游戏界面输出当前游戏进行信息,包括当前得分、当前关卡以及击中敌机数量。   (5)增加了鼠标控制战机位置这一效果,战绩的位置随着鼠标的移动而移动,并且点击鼠标左键可使得战机发射子弹。   (6)实现了暂停游戏的功能,玩家可通过键盘上的‘Z’键,对游戏进行暂停。   (7)通过对话框的弹出可提示玩家是否查看游戏说明、是否进入下一关、是否重新开始等消息,使得玩家可自己选择。 2. 相关技术 2.1 Windows定时器技术   Windows定时器是一种输入设备,它周期性地在每经过一个指定的时间间隔后就通知应用程序一次。程序将时间间隔告诉Windows,然后Windows给您的程序发送周期性发生的WM_TIMER消息以表示时间到了。本程序中使用多个定时器,分别控制不同的功能。在MFC的API函数中使用SetTimer()函数设置定时器,设置系统间隔时间,在OnTimer()函数中实现响应定时器的程序。 2.2 透明贴图实现技术   绘制透明位图的关键就是创建一个“掩码”位图(mask bitmap),这个“掩码”位图是一个单色位图,它是位图中图像的一个单色剪影。   在详细介绍实现过程之前先介绍下所使用的画图函数以及函数参数所代表的功能;整个绘制过程需要使用到BitBlt()函数。整个功能的实现过程如下:    (1) 创建一张大小与需要绘制图像相同的位图作为“掩码”位图;    (2) 将新创建的“掩码”位图存储至掩码位图的设备描述表中;    (3) 把位图设备描述表的背景设置成“透明色”,不需要显示的颜色;    (4) 复制粘贴位图到“掩码”位图的设备描述表中,这个时候“掩码”位图设备描述表中存放的位图与位图设备描述表中的位图一样;    (5) 把需要透明绘制的位图与对话框绘图相应区域的背景进行逻辑异或操作绘制到对话框上;    (6) 把“掩码”位图与这个时候对话框相应区域的背景进行逻辑与的操作;    (7) 重复步骤5的操作,把需要透明绘制的位图与对话框绘图相应区域的背景进行逻辑异或操作绘制到对话框上;    (8) 最后把系统的画笔还给系统,删除使用过的GDIObject,释放非空的指针,最后把新建的设备描述表也删除。 2.3 CObList链表 MFC类库中提供了丰富的CObList类的成员函数,此程序主要用到的成员函数如下:(1) 构造函数,为CObject指针构造一个空的列表。 (2) GetHead(),访问链表首部,返回列表中的首元素(列表不能为空)。(3) AddTail(),在列表尾增加一个元素或另一个列表的所有元素。   (4) RemoveAll(),删除列表中所有的元素。   (5) GetNext(),返回列表中尾元素的位置。   (6) GetHeadPosition(),返回列表中首元素的位置。   (7) RemoveAt(),从列表中删除指定位置的元素。   (8) GetCount(),返回列表中的元素数。 在CPlaneGameView.h文件中声明各游戏对象与游戏对象链表:   (1)//创建各游戏对象 CMyPlane *myplane; CEnemy *enemy; CBomb *bomb; CBall *ball; CExplosion *explosion; (2)//创建存储游戏对象的对象链表 CObList ListEnemy; CObList ListMe; CObList ListBomb; CObList ListBall; CObList ListExplosion; 2.4获取矩形区域   首先,使用CRect定义一个对象,然后使用GetClientRect(&对象名)函数,获取界面的矩形区域rect.Width() 为矩形区域的宽度,rect.Height()为矩形区域的高度。   使用IntersectRect(&,&))函数来判断两个源矩形是否有重合的部分。如果有不为空,则返回非零值;否则,返回0。 2.5使用AfxMessageBox显示游戏过程中的提示信息   AfxMessageBox()是模态对话框,你不进行确认时程序是否往下运行时,它会阻塞你当前的线程,除非你程序是多线程的程序,否则只有等待模态对话框被确认。   在MFC中,afxmessagebox是全局的对话框最安全,也最方便。 2.6内存释放   在VC/MFC用CDC绘图时,频繁的刷新,屏幕会出现闪烁的现象,CPU时间占用率相当高,绘图效率极低,很容易出现程序崩溃。及时的释放程序所占用的内存资源是非常重要的。   在程序中使用到的链表、刷子等占用内存资源的对象都要及时的删除。Delete Brush, List.removeall()等。 2.7 CImageList处理爆炸效果   爆炸效果是连续的显示一系列的图片。如果把每一张图片都显示出来的话,占用的时间是非常多的,必然后导致程序的可行性下降。CImageList是一个“图象列表”是相同大小图象的集合,每个图象都可由其基于零的索引来参考。可以用来存放爆炸效果的一张图片,使用Draw()函数来绘制在某拖拉操作中正被拖动的图象,即可连续绘制出多张图片做成的爆炸效果。 2.8对话框的应用    在设置游戏难度、炸弹的速度等,使用对话框进行设置非常方便,又体现出界面的友好。    对话框的应用过程如下:    (1). 资源视图下,添加Dialog对话框。然后添加使用到的控件,并修改控件的ID以便于后面的使用。    (2). 为对话框添加类,在对话框模式下,点击项目,添加类。    (3). 在类视图中,为对话框类添加成员变量(控件变量)。设置变量的名称、类型、最值等信息。    (4). 在资源视图菜单中,选择相应的菜单项,右击添加时间监听程序,设置函数处理程序名称。    (5). 在处理程序函数中添加相应的信息。 3. 总体设计与详细设计 3.1 系统模块划分   该飞机大战游戏程序分为游戏背景位图绘制模块、各游戏对象绘制模块、游戏对象之间的碰撞模块、爆炸效果产生模块、游戏界面输出玩家得分关卡信息模块。   其中在游戏对象绘制模块中,战机是唯一对象,在游戏开始时产生该对象,赋予其固定的生命值,当其与敌机对象、敌机炸弹碰撞时使其生命值减一,直至生命值为零,便删除战机对象。敌机对象与敌机炸弹对象的绘制中采用定时器技术,定时产生。爆炸对象初始化为空,当游戏过程中即时发生碰撞时,在碰撞位置产生爆炸对象,添加到爆炸链表中。 3.2 主要功能模块 3.2.1 系统对象类图            CGameObject是各个游戏对象的抽象父类,继承自CObject类,其他的类:战机类、敌机类、爆炸类、子弹类、炸弹类、文字类都继承了此类。   每个游戏对象类中既继承了来自父类CGameObject的属性,又有自己的特有属性和方法。 3.2.2 系统主程序活动图    3.2.3 系统部分流程图 (1) 该飞机大战游戏执行流程图: (2) 利用定时器定时产生敌机并绘制敌机流程图 4. 编码实现 4.1 绘制游戏背景位图程序   CDC *pDC=GetDC();   //获得矩形区域对象   CRect rect;   GetClientRect(▭);   //设备环境对象类----CDC类。   CDC cdc;   //内存中承载临时图像的位图   CBitmap bitmap1;   //该函数创建一个与指定设备兼容的内存设备上下文环境(DC)   cdc.CreateCompatibleDC(pDC);   //该函数创建与指定的设备环境相关的设备兼容的位图。   bitmap1.CreateCompatibleBitmap(pDC,rect.Width(),rect.Height());   //该函数选择一对象到指定的设备上下文环境中,该新对象替换先前的相同类型的对象。   CBitmap *pOldBit=cdc.SelectObject(&bitmap1;);   //用固定的固体色填充文本矩形框   cdc.FillSolidRect(rect,RGB(51,255,255)); //添加背景图片   CBitmap bitmap_BackGround;   bitmap_BackGround.LoadBitmap(IDB_BACKGROUND);   BITMAP bimap2;//位图图像   bitmap_BackGround.GetBitmap(&bimap2;);   CDC cdc_BackGround;//定义一个兼容的DC   cdc_BackGround.CreateCompatibleDC(&cdc;);//创建DC   CBitmap*Old=cdc_BackGround.SelectObject(&bitmap;_BackGround);   cdc.StretchBlt(0,0,rect.Width(),rect.Height(),&cdc;_BackGround,0,0,bimap2.bmWidth,bimap2.bmHeight,SRCCOPY); 4.2 飞机大战游戏对象的绘制程序 //画战机对象(唯一) if(myplane!= NULL) { myplane->Draw(&cdc;,TRUE); } //设置定时器,随机添加敌机,敌机随机发射炸弹,此时敌机速度与数量和关卡有关 SetTimer(2,300,NULL);//敌机产生的定时器 SetTimer(3,500,NULL);//敌机炸弹产生的定时器   if(myplane!=NULL&& is_Pause == 0) { switch(nIDEvent) { case 2://设置定时器产生敌机 { if(pass_Num == 1)//第一关 { int motion =1;//设置敌机的方向,从上方飞出 CEnemy *enemy=new CEnemy(motion); ListEnemy.AddTail(enemy);//随机产生敌机 }//if else if(pass_Num >= 2)//第一关以后的关卡 { int motion1 = 1; //设置敌机的方向,从上方飞出 CEnemy *enemy1=new CEnemy(motion1); enemy1->SetSpeed_en((rand()%5 +1)* pass_Num); ListEnemy.AddTail(enemy1);//随机产生敌机 int motion2 = -1;//设置敌机的方向,从下方飞出 CEnemy *enemy2=new CEnemy(motion2); enemy2->SetSpeed_en((rand()%5 +1)* pass_Num); ListEnemy.AddTail(enemy2);//随机产生敌机 }//else if }//case break; }//switch //判断产生的敌机是否出界,若已经出界,则删除该敌机 POSITION posEn=NULL,posEn_t=NULL; posEn=ListEnemy.GetHeadPosition(); int motion = 1; while(posEn!=NULL) { posEn_t=posEn; CEnemy *enemy= (CEnemy *)ListEnemy.GetNext(posEn); //判断敌机是否出界 if(enemy->GetPoint().xGetPoint().x>rect.right ||enemy->GetPoint().yGetPoint().y>rect.bottom) { ListEnemy.RemoveAt(posEn_t); delete enemy; }//if else { enemy->Draw(&cdc;,TRUE); switch(nIDEvent) { case 3://设置定时器产生敌机炸弹 {   CBall*ball=newCBall(enemy->GetPoint().x+17,   enemy->GetPoint().y+30,enemy->GetMotion()); ListBall.AddTail(ball); }//case break; }//switch }//else }//while //判断产生的敌机炸弹是否出界,若已经出界,则删除该敌机炸弹 POSITION posball=NULL,posball_t=NULL; posball= ListBall.GetHeadPosition(); while(posball!=NULL) { posball_t=posball; ball= (CBall *) ListBall.GetNext(posball); if( ball->GetPoint().xGetPoint().x>rect.right || ball->GetPoint().yGetPoint().y>rect.bottom) { ListBall.RemoveAt(posball_t); delete ball; }//if else { ball->Draw(&cdc;,1); }//else }//while }//if 4.3 飞机大战游戏对象战机位置的动态控制 if(myplane!= NULL) { myplane->Draw(&cdc;,TRUE); } //获得键盘消息,战机位置响应,战机速度speed为30 if((GetKeyState(VK_UP) <0 || GetKeyState('W') GetPoint().ySetPoint( myplane->GetPoint().x,rect.bottom); else myplane->SetPoint(myplane->GetPoint().x,( myplane->GetPoint().y - speed) ); }//if if((GetKeyState(VK_DOWN) <0|| GetKeyState('S') < 0)&& is_Pause== 0)//下方向键{}//if if((GetKeyState(VK_LEFT) <0|| GetKeyState('A') < 0)&& is_Pause== 0)//左方向键{}//if if((GetKeyState(VK_RIGHT) <0|| GetKeyState('D') < 0)&& is_Pause== 0)//右方向键{}//if if((GetKeyState(VK_SPACE)GetPoint().x, myplane->GetPoint().y,1); ListBomb.AddTail(BombOne); CBomb*BombTwo=newCBomb(myplane->GetPoint().x+35, myplane->GetPoint().y,1); ListBomb.AddTail(BombTwo); PlaySound((LPCTSTR)IDR_WAVE2,AfxGetInstanceHandle(),SND_RESOURCE |SND_ASYNC); }//if if(GetKeyState('Z')SetPoint(point.x,point.y); } //鼠标控制战机,发射战机子弹 void CPlaneGameView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CView::OnLButtonDown(nFlags, point); if( is_Pause == 0) { CBomb *BombOne=new CBomb( myplane->GetPoint().x, myplane->GetPoint().y,1); PlaySound((LPCTSTR)IDR_WAVE2, AfxGetInstanceHandle(), SND_RESOURCE |SND_ASYNC); ListBomb.AddTail(BombOne); CBomb *BombTwo=new CBomb( myplane->GetPoint().x+35, myplane->GetPoint().y,1); ListBomb.AddTail(BombTwo); } } 4.4 飞机大战游戏对象之间的碰撞实现 本飞机大战游戏中的碰撞考虑了飞机子弹打中敌机、敌机炸弹打中战机、战机与敌机相撞、敌机炸弹与战机子弹相撞四种情况,根据游戏对象的矩形区域是否有交叉,而确认两者是否相撞,而产生爆炸对象,添加到爆炸链表中。以战机与敌机相撞为例: if(myplane != NULL&& is_Pause== 0) { POSITION enemyPos,enemyTemp; for(enemyPos= ListEnemy.GetHeadPosition();(enemyTemp=enemyPos)!=NULL;) { enemy =(CEnemy *) ListEnemy.GetNext(enemyPos); //获得敌机的矩形区域 CRect enemyRect = enemy->GetRect(); //获得战机的矩形区域 CRect myPlaneRect = myplane->GetRect(); //判断两个矩形区域是否有交接 CRect tempRect; if(tempRect.IntersectRect(&enemyRect;,myPlaneRect)) { CExplosion *explosion = new CExplosion( enemy->GetPoint().x+18 , enemy->GetPoint().y + 18); PlaySound((LPCTSTR)IDR_WAVE,AfxGetInstanceHandle(), SND_RESOURCE |SND_ASYNC); ListExplosion.AddTail(explosion); //战机生命值减一 lifeNum_Me--; //删除敌机 ListEnemy.RemoveAt(enemyTemp); delete enemy; if(lifeNum_Me == 0) { //删除战机对象 delete myplane; myplane=NULL; }//if break; }//if }//for }//if 战机子弹打中敌机、敌机炸弹打中战机以及战机子弹与敌机炸弹对象的碰撞实现同上。 4.5 游戏界面输出当前信息   if(myplane != NULL&& is_Pause== 0)    {    HFONT font;    font=CreateFont(20,10,0,0,0,0,0,0,0,0,0,100,10,0);    cdc.SelectObject(font);    CString str;    cdc.SetTextColor(RGB(255,0,0));    str.Format(_T("当前关卡:%d"),pass_Num);    cdc.TextOutW(10,20,str);    str.Format(_T("当前得分:%d"),score_Me);    cdc.TextOutW(10,40,str);    str.Format(_T("剩余生命:%d"),lifeNum_Me);    cdc.TextOutW(10,60,str);    }//if    if(myplane !=NULL && lifeNum_Me >0)    {    if(score_Me > 10*count_Life*pass_Num)    {    lifeNum_Me++;//生命值加1    count_Life++;//已增加生命值加1    }    } 游戏进入下一关,以及结束游戏界面设计代码与上类似。 5. 项目程序测试 5.1战机移动及子弹发射模块测试 用例 预期结果 实际结果 问题描述 修改方案 点击A键或鼠标左移 战机向左移动 战机向左移动 点击D键或鼠标右移 战机向右移动 战机向右移动 点击W键或鼠标上移 战机向上移动 战机向上移动 点击S键或鼠标上移 战机向下移动 战机向下移动 5.2敌机及炸弹模块测试 用例 预期结果 实际结果 问题描述 修改方案 玩家得分50(通过第一关后) 敌机从上下两方向均可飞出,且速度不断增加 敌机从上下两方向均可飞出,且速度不断增加 5.3爆炸模块测试 用例 预期结果 实际结果 问题描述 修改方案 战机子弹打中敌机 敌机位置处爆炸,敌机消失,战机生命-1 敌机位置处爆炸,敌机消失,战机生命-1 敌机炸弹打中战机 战机位置处爆炸,战机生命-1 战机位置处爆炸,战机生命-1 敌机战机相撞 敌机位置处爆炸,敌机消失,战机生命-1 敌机位置处爆炸,敌机消失,战机生命-1 战机子弹与敌机炸弹相撞 敌机炸弹处爆炸,子弹与炸弹均消失消失 敌机炸弹处爆炸,子弹与炸弹均消失消失 战机生命值==0 战机消失,GameOver或者过关 战机消失,GameOver或者过关 6. 实训中遇到的主要问题及解决方法   (1)由于对C++的面向对象的思想和逻辑思路不熟悉,不明白其中的封装之类的以及多态的思想,致使开始真正的进入实训接触到项目时没有开发思路,通过逐步查询书籍整理C++面向对象编程思路,才逐步理清项目的开发步骤。   (2)本飞机大战的游戏要求使用链表实现各游戏对象的存储和释放,由于链表知识掌握的不牢固,使用起来总是出现这样那样的错误,给整个游戏开发带来了很大的障碍,通过不断的调试修改,最终使程序正确运行。   (3)在绘制各种游戏对象—敌机和敌机炸弹时,开始使用随机函数,画出敌机时而很少,总是打不到预定的效果,后来经过修改使用定时器产生敌机和敌机炸弹,使整个游戏更加人性化。 7. 实训体会 (1)在本次飞机大战游戏项目的开发过程中遇到很多问题,大部分是因为对MFC编程的不熟悉以及链表掌握不牢固所导致的。 (2)MFC编程中有很多可以直接调用的函数,由于之前缺乏对这方面编程的经验,以至于本次项目开发过程中走了很多弯路。 (3)通过寻求老师和同学的帮助,解决了开发中遇到的很多问题,也提升了自己调试错误的能力。 (4)通过本次实训,使我熟悉了MFC编程技术、巩固了链表的使用方法并加深了对面向对象编程思想的理解,对以后程序的编写打下了良好的基础。
What is a DIB Section?
A DIB (Device Independent Bitmap) Section is a GDI object like a standard DIB but which additionally provides a pointer to the memory used to store the bitmap bits to which the creating application has direct access. This allows ultimate flexibility if you want to modify the bits of a bitmap.

Using DIB Sections
A DIB section is created using the GDI CreateDIBSection call. You need to modify the declare provided for this in the VB API guide because this declare assumes you cannot use the pointer to the bitmap returned by the function and simply discards it. Here are the declares you need:


Private Type BITMAPINFOHEADER '40 bytes
biSize As Long
biWidth As Long
biHeight As Long
biPlanes As Integer
biBitCount As Integer
biCompression As Long
biSizeImage As Long
biXPelsPerMeter As Long
biYPelsPerMeter As Long
biClrUsed As Long
biClrImportant As Long
End Type
Private Type BITMAPINFO
bmiHeader As BITMAPINFOHEADER
bmiColors As RGBQUAD
End Type

' Note - this is not the declare in the API viewer - modify lplpVoid to be
' Byref so we get the pointer back:
Private Declare Function CreateDIBSection Lib "gdi32" _
(ByVal hdc As Long, _
pBitmapInfo As BITMAPINFO, _
ByVal un As Long, _
lplpVoid As Long, _
ByVal handle As Long, _
ByVal dw As Long) As Long


To create the DIB Section, you initialise a BITMAPINFO structure with the required fields, which are all in the bmiHeader sub-structure:

Member Required Value
biSize Size of the BITMAPINFO structure
biWidth Width of the DIBSection in pixels

biHeight Height of the DIBSection in pixels

biPlanes Number of colour planes. Set to 1

biBitCount Bits per pixel. Set to 24 for true colour

biCompression Whether to use compression. If you want to work on the bits, set this to BI_RGB so the image is uncompressed
biSizeImage The size of the image in bytes. This is worked out from the width, height, number of bits per pixel. In a 24 bit image there are three bytes per pixel. Additionally, GDI requires that every horizontal line in the image aligns on a four byte boundary. So for a 24 bit image the ImageSize is biWidth*biHeight*3 rounded up to the nearest four bytes. You can round up to the width to the nearest four bytes as follows:
(.biWidth * 3 + 3) And &HFFFFFFFC



This allows you to create a DIB Section. You call CreateDIBSection like this:

hDib = CreateDIBSection( _
lHDC, _
m_tBI, _
DIB_RGB_COLORS, _
m_lPtr, _
0, 0)


Where:

hDib is a variable to receive the GDI handle to the DIB Section
lHDC is a valid DC, for example a Form's DC or the desktop DC

m_tBI is a the BITMAPINFO structure
m_lPtr is a variable to receive the pointer to the memory containing the bitmap bits.

To actually display a DIB Section, you must select it into a DC.

m_hDC = CreateCompatibleDC(0)
If (m_hDC <> 0) Then
If (CreateDIB(m_hDC, lWidth, lHeight, m_hDIb)) Then
m_hBmpOld = SelectObject(m_hDC, m_hDIb)
Create = True
Else
DeleteObject m_hDC
m_hDC = 0
End If
End If



Once it is in a DC you can then use BitBlt to paint it to another device context or to transfer the contents of another device context into it. Remember you must keep track of all the handles created in GDI so you can clear them up again when the DIBSection is no longer needed. To clear up, you need to:

Select the old bitmap (m_hBmpOld) back into the DC.
Delete the DIB section.
Delete the DC.
So far this has created a DIB which you can load with a graphic and display on the screen, but this achieves no more than you can do with a standard bitmap. The good stuff starts when you start modifying the bitmap bits.

Modifying the Bitmap Bits Directly
CreateDIBSection returns an address to the memory containing the bitmap. You can manipulate this directly through VB using a cool technique to make the memory look like a VB Byte array. This technique was originally presented in VBPJ article (Note the original article is no longer easily available). It uses a hidden VB call exposed by MSVBVM50.DLL (which is also available in VB6 - thanks to Paul Wilde for pointing this out) and the ubiquitous CopyMemory call. In my opinion, “CopyMemory” is the best language feature in VB (except that it isn't VB at all!)

Here are the declares you need:

Private Type SAFEARRAY2D
cDims As Integer
fFeatures As Integer
cbElements As Long
cLocks As Long
pvData As Long
Bounds(0 To 1) As SAFEARRAYBOUND
End Type
Private Declare Function VarPtrArray Lib "msvbvm50.dll" Alias "VarPtr" (Ptr() As Any) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)



To make the byte array point to the memory, you have to fill in the SAFEARRAY2D structure and then use CopyMemory as follows:

Dim tSA As SAFEARRAY2D
Dim bDib() As Byte

' Get the bits in the from DIB section:
With tSA
.cbElements = 1
.cDims = 2
.Bounds(0).lLbound = 0
' Height of the bitmap
.Bounds(0).cElements = m_tBI.bmiHeader.biHeight
.Bounds(1).lLbound = 0
' Width of the bitmap in bits (see earlier):
.Bounds(1).cElements = BytesPerScanLine()
.pvData = m_lPtr
End With
' Make the bDib() array point to the memory addresses:
CopyMemory ByVal VarPtrArray(bDib()), VarPtr(tSA), 4



Now the bDib() array is a two dimensional array with the first dimension being the x values and the second being the y values. A 24 bit DIB section is arranged so the bytes run Blue, Green, Red and remember that since the array is padded to a DWORD boundary there may be up to three unused bytes at the end of each row. So, for example, to set the top left pixel to purple you would write this:

bDib(0,0) = 255 ' Blue
bDib(1, 0) = 0 ' Green
bDib(2, y) = 255 ' Red



Once you have finished with the bDib array, you need to be sure to clear up the SAFEARRAY pointer you have created. If you fail to do this, your code will work under Win9x but will crash NT4.0:

CopyMemory ByVal VarPtrArray(bDib), 0&, 4


Enough of That, I Want to Use It
That covers the theory of using DIB Sections. To make it easy, I include a self-contained class (cDibSection) which you can include. The implementation is as follows:

Method Description
BytesPerScanLine Returns the number of bytes horizontally, taking into account the bits per pixel and 4 byte boundary padding.
ClearUp Frees up any GDI objects held by the class. Called automatically when the class terminates.
CopyToClipboard Does as it says!
Create Creates a DIB section of the specified width and height in pixels.
CreateFromPicture Creates a DIB section the same size as a VB picture object and copies the bitmap in it into the DIB section.
DIBSectionBitsPtr Returns the address of the DIBSection's bits in memory.
hdc Returns the memory device context used by the class to hold the DIB Section. You can use this in GDI operations, but do not call DeleteObject on it.
hDib Returns a handle to the DIBSection held by the class. You can use this in GDI operations, but do not call DeleteObject on it.
Height Returns the Height of the DIBSection in pixels.
LoadPictureBlt Copies all or a part of a picture from another Device Context into the DIB section.
PaintPicture Similar to the VB paint picture method, this copies all or part of the DIB section to another device context using the specified Raster Operation.
RandomiseBits Randomises the pixels in the DIB Section, either to random colours or gray scaled.
Resample Resizes the DIB using linear interpolation to create a smoother resized version than you would get if you used StretchBlt.
Width Returns the width of the DIB in pixels.


A Simple Fade Example
This demonstrates how to fade out a bitmap. It should run as a real-time animation, provided the image size isn't too big. I've found that images which are too large don't show as a smooth animation even when the fade code runs quickly enough because BitBlt tends to "tear". This occurs because BitBlt doesn't completely display the bitmap during a single screen refresh and therefore the image is partially displayed before the refresh occurs. To get round this problem you need to use DirectX.

This sample is simplified version of the static and fade example available for download on the Image Processing using DIB Sections page.

To try this sample, create a new project and add the cDIBSection class to it. Copy the declares for CopyMemory, VarPtrArray and SAFEARRAY2D into the project's form.

Then add this sub:

Private Sub Fade( _
ByRef cTo As cDIBSection, _
ByVal lAmount As Long _
)
Dim bDib() As Byte
Dim x As Long, y As Long
Dim xMax As Long, yMax As Long
Dim lB As Long, lG As Long, lR As Long
Dim lA As Long, lA2 As Long
Dim lTIme As Long
Dim tSA As SAFEARRAY2D

' have the local matrix point to bitmap pixels
With tSA
.cbElements = 1
.cDims = 2
.Bounds(0).lLbound = 0
.Bounds(0).cElements = cTo.Height
.Bounds(1).lLbound = 0
.Bounds(1).cElements = cTo.BytesPerScanLine
.pvData = cTo.DIBSectionBitsPtr
End With
CopyMemory ByVal VarPtrArray(bDib), VarPtr(tSA), 4

yMax = cTo.Height - 1
xMax = cTo.Width - 1

For x = 0 To (xMax * 3) Step 3
For y = 0 To yMax
lB = lAmount * bDib(x, y) \ 255
lG = lAmount * bDib(x + 1, y) \ 255
lR = lAmount * bDib(x + 2, y) \ 255
bDib(x, y) = lB
bDib(x + 1, y) = lG
bDib(x + 2, y) = lR
Next y
Next x

CopyMemory ByVal VarPtrArray(bDib), 0&, 4

End Sub


Add a Command Button to the Form, and put this code behind it:

Private Sub Command1_Click()

Dim cDib As New cDibSection
Dim cDibBuffer as New cDibSection
Dim i As Long

' Load the picture to fade:
Set sPic = LoadPicture("Put Your File Here!")
cDib.CreateFromPicture sPic

' Create a copy of it:
cDibBuffer.Create cDib.Width, cDib.Height
cDib.PaintPicture cDibBuffer.HDC

' Fade Loop:
For i = 0 To 255 Step 4
' Fade the dib by amount i:
Fade cDib, i
' Draw it:
cDib.PaintPicture Form1.hDC
' Breathe a little. You may have to put a slowdown here:
DoEvents
' Reset for next fade:
cDibBuffer.PaintPicture cDib.HDC
Next i

End Sub



Now run the code. When you click the button, the image will be faded as fast as your system allows. The code will run slowly in the IDE but will go much much quicker if you compile it to native code. Also, checking all the Advanced Optimisation settings will make it run about 60% faster again! On my machine (PII 266 with 8Mb Xpert@Work card) it does 40fps when working on a 256x256 pixel image.



API之网络函数1. API之网络函数 WNetAddConnection 创建同一个网络资源的永久性连接 WNetAddConnection2 创建同一个网络资源的连接 WNetAddConnection3 创建同一个网络资源的连接 WNetCancelConnection 结束一个网络连接 WNetCancelConnection2 结束一个网络连接 WNetCloseEnum 结束一次枚举操作 WNetConnectionDialog 启动一个标准对话框,以便建立同网络资源的连接 WNetDisconnectDialog 启动一个标准对话框,以便断开同网络资源的连接 WNetEnumResource 枚举网络资源 WNetGetConnection 获取本地或已连接的一个资源的网络名称 WNetGetLastError 获取网络错误的扩展错误信息 WNetGetUniversalName 获取网络中一个文件的远程名称以及/或者UNC(统一命名规范)名称 WNetGetUser 获取一个网络资源用以连接的名字 WNetOpenEnum 启动对网络资源进行枚举的过程 2. API之消息函数 BroadcastSystemMessage 将一条系统消息广播给系统中所有的顶级窗口 GetMessagePos 取得消息队列中上一条消息处理完毕时的鼠标指针屏幕位置 GetMessageTime 取得消息队列中上一条消息处理完毕时的时间 PostMessage 将一条消息投递到指定窗口的消息队列 PostThreadMessage 将一条消息投递给应用程序 RegisterWindowMessage 获取分配给一个字串标识符的消息编号 ReplyMessage 答复一个消息 SendMessage 调用一个窗口的窗口函数,将一条消息发给那个窗口 SendMessageCallback 将一条消息发给窗口 SendMessageTimeout 向窗口发送一条消息 SendNotifyMessage 向窗口发送一条消息 3. API之文件处理函数 CloseHandle 关闭一个内核对象。其中包括文件、文件映射、进程、线程、安全和同步对象等 CompareFileTime 对比两个文件的时间 CopyFile 复制文件 CreateDirectory 创建一个新目录 CreateFile 打开和创建文件、管道、邮槽、通信服务、设备以及控制台 CreateFileMapping 创建一个新的文件映射对象 DeleteFile 删除指定文件 DeviceIoControl 对设备执行指定的操作 DosDateTimeToFileTime 将DOS日期和时间值转换成一个 win32 FILETIME 值 FileTimeToDosDateTime 将一个 win32 FILETIME 值转换成DOS日期和时间值 FileTimeToLocalFileTime 将一个FILETIME结构转换成本地时间 FileTimeToSystemTime 根据一个FILETIME结构的内容,装载一个SYSTEMTIME结构 FindClose 关闭由FindFirstFile函数创建的一个搜索句柄 FindFirstFile 根据文件名查找文件 FindNextFile 根据调用FindFirstFile函数时指定的一个文件名查找下一个文件 FlushFileBuffers 针对指定的文件句柄,刷新内部文件缓冲区 FlushViewOfFile 将写入文件映射缓冲区的所有数据都刷新到磁盘 GetBinaryType 判断文件是否可以执行 GetCompressedFileSize 判断一个压缩文件在磁盘上实际占据的字节数 GetCurrentDirectory 在一个缓冲区中装载当前目录 GetDiskFreeSpace 获取与一个磁盘的组织有关的信息,以及了解剩余空间的容量 GetDiskFreeSpaceEx 获取与一个磁盘的组织以及剩余空间容量有关的信息 GetDriveType 判断一个磁盘驱动器的类型 GetExpandedName 取得一个压缩文件的全名 GetFileAttributes 判断指定文件的属性 GetFileInformationByHandle 这个函数提供了获取文件信息的一种机制 GetFileSize 判断文件长度 GetFileTime 取得指定文件的时间信息 GetFileType 在给出文件句柄的前提下,判断文件类型 GetFileVersionInfo 从支持版本标记的一个模块里获取文件版本信息

15,979

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 界面
社区管理员
  • 界面
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧