简体   繁体   中英

winapi: from HDC to an HBITMAP

I would like to do something which I believe is fairly simple but since I am new to the winapi I am finding a lot of problems. Basically I have an HDC (which I am BitBlitting from a loaded Bitmap) and I am drawing a rectangle on it. Then I would like to BitBlt that HDC onto a new HBITMAP Object, but alas for now to no avail.

Here is my code which I have been trying to get to work for a couple of hours now

BITMAPINFO info;
Bitmap *tempbmp = Bitmap::FromFile(L"C:\\Users\\abelajc\\Pictures\\BackgroundImage.png", false);
HBITMAP loadedbackground;
tempbmp->GetHBITMAP(NULL, &loadedbackground);

HBRUSH hRed = CreateSolidBrush(RGB(255, 0, 0));

HDC pDC = GetDC(0);
HDC TmpDC = CreateCompatibleDC(pDC); //main DC on which we will paint on

HDC dcBmp = CreateCompatibleDC(TmpDC); //DC for the loadedbackground HBitmap
HGDIOBJ TmpObj2 = SelectObject(dcBmp , tempbmp); //Selecting Bitmap in DC
BitBlt(TmpDC, 0, 0, 512, 512, dcBmp, 0, 0, SRCCOPY);
SelectObject(dcBmp, TmpObj2); //Deselecting Bitmap from DC
DeleteDC(dcBmp);

RECT rectangle;
SetRect(&rectangle, 5, 5, 20, 20);
FillRect(TmpDC, &rectangle, hRed);

HDC hCompDC = CreateCompatibleDC(TmpDC);
HBITMAP hBmp = CreateCompatibleBitmap(TmpDC, 512, 512);
HBITMAP hOld = (HBITMAP)SelectObject(hCompDC, hBmp);
BitBlt(hCompDC, 0, 0, 512, 512, TmpDC, 0, 0, SRCCOPY);
SelectObject(hCompDC, hOld);
DeleteDC(hCompDC);

Bitmap *image = new Bitmap(hBmp, NULL);

I think you just need some clarification about GDI.
A DC is exactly what its name imply : a device context. It's just a context, nothing concrete. Some DCs are context to a real graphic device, some others (memory DCs) are context to a virtual graphic surface in memory. The DCs you create with CreateCompatibleDC are memory DC, but creating the DC only create the context, not the memory surface. As the MSDN documentation says :

Before an application can use a memory DC for drawing operations, it must select a bitmap of the correct width and height into the DC.

You need to associate a HBITMAP with the DC. After doing that, you can consider that drawing to the DC is essentially drawing to the bitmap. The memory DC is the 'window' to the bitmap.

Once you understand that, you will see that your program can be greatly shortened. Feel free to comment if you still have problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM