所以,我对WinAPI非常陌生,我成功地加载了一个精灵,我可以用箭头键移动它。我的老师告诉我要非常小心的‘内存泄漏’,我不知道如何释放内存的正确方式,因为C++已经为我做了当我做控制台编程。我运行了这个程序,在移动角色一段时间后,它冻结了我的电脑一分钟,所以我想我做错了什么。你能告诉我如何正确释放内存(如果我做错了),如果我的位图方法有什么坏的地方需要优化?谢谢!这是密码。
void LoadAndBlitBitmap(LPCSTR szFileName, HWND hwnd, HDC winDC, int xPos, int yPos)
{
//DEFINITIONS
/*TransparentBlt(destDC, destXpos, destYpos, sizeX, sizeY, srcDC, 0, 0, sizeX, sizeY, RGB(a, b, c)) = TRANSPARENT BITMAP BLIT. Ex. RGB(255, 255, 255) if background is white*/
/*BitBlt(destDC, destXpos, destYpos, sizeX, sizeY, srcDC, 0, 0, SRCCOPY); = SOLID BITMAP BLIT WITH NO TRANSPARENCY*/
//END DEFINITIONS
//-----Get the size of the window---------
RECT rect;
int win_width = 0;
int win_height = 0;
if(GetWindowRect(hwnd, &rect))
{
win_width = rect.right - rect.left; //Subtracting the right coordinate with the left gives the width
win_height = rect.bottom - rect.top; //Subtracting the bottom coordinate with the top gives the height
}
//----------------------------------------
HDC hdcMem = CreateCompatibleDC(winDC); //Create the DC that will hold the off-screen printing. (Double Buffering "Anti-Flicker" Method)
HBITMAP hbmMem = CreateCompatibleBitmap(winDC, win_width, win_height); //Create the bitmap with the size of the window
HANDLE hOld = SelectObject(hdcMem, hbmMem); //Set the paintable bitmap to the off-screen DC
//Draw to the off-screen DC
HBITMAP bitmap = (HBITMAP)LoadImage(NULL, szFileName, IMAGE_BITMAP, 69, 69, LR_LOADFROMFILE); //Load the .bmp from a file
HDC blockDC = CreateCompatibleDC(NULL); //Create a DC to hold the .bmp
SelectObject(blockDC, bitmap); //Select the .bmp to the DC
TransparentBlt(hdcMem, xPos, yPos, 69, 69, blockDC, 0, 0, 69, 69, RGB(255, 255, 255)); //Blit the .bmp to the DC*/
//Transfer off-screen DC to the screen
BitBlt(winDC, 0, 0, win_width, win_height, hdcMem, 0, 0, SRCCOPY);
// Uninitialize and deallocate resources
SelectObject(hdcMem, hOld);
DeleteDC(hdcMem);
SelectObject(blockDC, hOld);
DeleteDC(blockDC);
DeleteObject(bitmap);
}发布于 2013-09-25 23:30:28
有两件事是错误的:
SelectObject(blockDC, hOld);hOld不是来自blockDC,而是来自hdcMem。您甚至没有从blockDC中保存旧的位图。改为:
HBITMAP hOld2 = SelectObject(blockDC, bitmap);
// and
SelectObject(blockDC, hOld2);其次,您不能在任何地方删除hbmMem。在底部加上:
DeleteObject(hbmMem);实际上,第三件事也是错误的--您没有检查您所做的任何API调用是否失败。您应该检查CreateCompatibleDC是否返回NULL,如果返回,则中止和清除。
https://stackoverflow.com/questions/19016834
复制相似问题