简体   繁体   English

winapi:从HDC到HBITMAP

[英]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. 我想做一些我认为很简单的事情,但是由于我是winapi的新手,所以发现了很多问题。 Basically I have an HDC (which I am BitBlitting from a loaded Bitmap) and I am drawing a rectangle on it. 基本上,我有一个HDC(我是从已加载的位图进行BitBlitting),并在其上绘制一个矩形。 Then I would like to BitBlt that HDC onto a new HBITMAP Object, but alas for now to no avail. 然后我想将HDC的BitBlt放到一个新的HBITMAP对象上,但是可惜现在还是无济于事。

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. 我认为您只需要对GDI进行一些澄清。
A DC is exactly what its name imply : a device context. DC正是其名称所隐含的含义:设备上下文。 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. 一些DC是实际图形设备的上下文,另一些DC(内存DC)是内存中虚拟图形表面的上下文。 The DCs you create with CreateCompatibleDC are memory DC, but creating the DC only create the context, not the memory surface. 使用CreateCompatibleDC创建的DC是内存DC,但是创建DC仅创建上下文,而不创建内存表面。 As the MSDN documentation says : 正如MSDN文档所说:

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. 在应用程序可以使用内存DC进行绘制操作之前,它必须在DC中选择正确宽度和高度的位图。

You need to associate a HBITMAP with the DC. 您需要将HBITMAP与DC关联。 After doing that, you can consider that drawing to the DC is essentially drawing to the bitmap. 之后,您可以认为绘制到DC实质上是绘制到位图。 The memory DC is the 'window' to the bitmap. 内存DC是位图的“窗口”。

Once you understand that, you will see that your program can be greatly shortened. 一旦了解了这一点,您就会发现您的程序可以大大缩短。 Feel free to comment if you still have problems. 如果您仍有问题,请随时发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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