I'm wondering , if I want to create different bitmaps,
I use the CreateCompatibleBitmap function again and again, to associate it to the same memory CDC.
is it the same meaning that I CreateBitmap and SelectObject again and again??
I ask this question because I want to do something to the newly created bitmap by another CDC.
Without seeing the specific code it's hard to know the exact problem but CreateCompatibleBitmap is commonly used in double-buffering situations to avoid flickering. Rather than drawing directly to the Device Context (DC) you first draw to an off-screen, or memory, DC which is basically drawing to a bitmap. The bitmap is then copied directly to the screen DC using BitBlt, so it appears like all the drawing happens at the same time.
The usual steps are this (and will probably happen on every WM_PAINT):
Use the screen DC to create a bitmap, which is 'compatible' with it, using CreateCompatibleBitmap.
Create a memory DC
Select the bitmap into the memory DC (this is what you'll draw to)
When drawing is finished BitBlt the memory DC's bitmap onto the screen DC.
More information available here: Guide to Win32 Memory DC (Code Project)
Yes, CreateCompatibleBitmap() creates a new bitmap, a new memory allocation, a new handler each time you call it in a loop;
Related
We're currently shifting an older application to draw through GDI+, instead of using GDI directly. As we are progressively translating teh system as we go, sometimes we need to grab a HDC from a Gdiplus::Graphics object in order to allow code which hasn't been translated yet to draw straight to it using GDI.
The drawing happens fine, except we seem to be losing antialias on images drawn directly to the DC using GDI. If, after grabbing the DC from the Graphics object, we draw a filled rectangle over the entire area, and then proceed with the drawing, it comes out fine. If we just get straight to drawing everything comes in without antialias.
void Draw(Gdiplus::Graphics& renderContext)
{
auto hdc = renderContext.GetHDC();
auto dc = HDC::FromHandle(nativeDC);
//Required to antialias drawing below
dc->FillSolidRect(GetClientRect(), RGB(255, 255, 255));
/* Do Drawing */
dc ->Detach();
renderContext.ReleaseHDC(hdc );
}
To be more precise, it seems like the antialias alpha get's flattened, which explains why filling a rectangle in GDI before drawing removes the artifacts.
It's a similar effect you might get if you draw with antialias on onto one Bitmap, and then try to alphablend it on top of another Bitmap - the alpha information on the top gets flattened and then the new alpha value specified in a ColorMatrix is applied to the whole image.
If anyone could provide some insight into what exactly is going on when you grab/release a HDC from a graphics object, and why drawing with GDI directly looses the alpha, I'd be appreciated.
The bitmap backing the HDC is a copy, not the original, as described here.
Using GDI on a GDI+ Graphics Object Backed by a Bitmap
When Graphics::GetHDC() is called for a Graphics object that is backed
by a bitmap rather than the screen, a memory HDC is created and a new
HBITMAP is created and selected into the memory HDC. This new memory
bitmap is not initialized with the original bitmap's image but rather
with a sentinel pattern, which allows GDI+ to track changes to the
bitmap. Any changes that are made to the memory bitmap through the use
of GDI code become apparent in changes to the sentinel pattern. When
Graphics::ReleaseHDC() is called, those changes are copied back to the
original bitmap... Also, there is a performance cost to this approach because
GDI+ must copy the changes back to the original bitmap.
Obviously when you draw on an HDC with GDI you won't get any antialiasing. GDI doesn't support it. That's what GDI+ is for.
I have a win32 application which was developed in c++. The application draws some stuff on the window using basic shapes (rectangles). The windows is repainted every 20ms (50hz) using InvalidateRect. All works well but the drawing is flickering. How can i prevent the flickering? In c# i normally use a double buffered component (such as pictureBox), how could i get rid of this in c++ using win32?
You can create an in-memory device context, draw those shapes to it (just like you would to the window's device context) and then blit from it to window's device context when the window is invalidated.
You also need to disable background clearing (handle WM_ERASEBKGND window message appropriately) before the draw happens.
Edit: I stumbled upon a pretty exhaustive tutorial on flicker-free drawing in GDI, which explains all aspects of drawing in Windows and comes with examples.
You can easily implement double buffering in Win32 as well. Assuming you are doing your painting directly on the Window using its device context, do this instead:
Create a "memory" device context and do all your drawing on that device context, then copy the invalidated portions of the window to the actual device context when appropriate, using the BitBlt() function
There's a pretty good (albeit high level) overview here.
You can double buffer in C++, too.
When you get the DC to paint to, you create an offscreen bitmap (CreateCompatibleBitmap) and a memory DC (CreateCompatibleDC). Do all your painting to that DC. At the end, do a BitBlt from the memory DC to the actual DC.
For performance, you might want to cache the offscreen bitmap and DC, but remember to recreate them when the window size changes.
Here's the greatest tutorial i've found yet:
https://msdn.microsoft.com/en-us/library/ms969905.aspx
In short - yes, you have to implement the double-buffering. It's done through creating the in-memory DC and then drawing everything you want to an in-memory bitmap using that DC, only afterwards commiting this bitmap to an actual DC.
It's only for 'debugging' purposes, so I don't want to spend a lot of time with this, nor it is very important. The program exports the data as a png, jpg, svg, etc... -so it's not a big deal, though it could be good to see the image while it is being generated. Also, the program is going to be used in a Linux server; but I'll limit this 'feature' to the Win version.
I also don't want to use a library, except if it is very, very lightweight (I used CImg for a while, but I wasn't very happy with its speed, so I ended up writing the important functions myself and just using libjpeg and libpng directly).
I have the image in an ARGB format (32bpp), though converting the format won't be a problem at all. I would like to use Win32, creating a window from a function deep inside the code (no known hInstance, etc), and writing the bitmap. Fast and easy, hopefully.
But I don't know the win32api enough. I've seen that the only option to draw (GDI) is trough a HBITMAP object... Any code snippet or example I can rely on? Any consideration I might not overlook? Or maybe -considering my time constrains- should I just forget it?
Thanks!
The biggest piece of work here is actually registering the window class and writing a minimal window procedure. But if this is debug only code, you can actually skip that part. (I'll come back to that later).
If you have an HBITMAP, then you would use BitBlt or StretchBlt to draw it, but if you don't already have the image as an HBITMAP, then StretchDIBits is probably a better choice since you can use it if you only have a pointer to the bitmap data. You have to pass it a source and destination rectangle, a BITMAPINFOHEADER and a pointer to the raw bitmap data. Something like this
SIZE sBmp = { 100, 200 };
LPBITMAPINFOHEADER pbi; // the bitmap header from the file, etc.
LPVOID pvBits; // the raw bitmap bits
StretchDIBits (hdc, 0, 0, sBmp.cx, sBmp.cy,
0, 0, sBmp.cx, sBmp.cy,
pvBits, pbi,
DIB_RGB_COLORS,
SRCCOPY);
So the next part is how do I get a HDC to draw in? Well for Debug code, I often draw directly to the screen. HDC hdc = GetDC(NULL) will get a DC that can draw to the screen, but there are security issues and it doesnt' work the same with Aero in Windows Vista, so the other way is to draw onto a window. If you have a window that you can just draw over, then HDC hdc = GetDC(hwnd) will work.
The advantage of doing it this way is that you don't have to create and show a window, so it's less disruptive of code flow, It's helpful for debugging a specific problem, but not the sort of thing you can leave turned on all of the time.
For a longer term solution, You could create a dialog box and put your bitmap drawing call in the WM_PAINT or WM_ERASEBKGND message handler for the dialog box. But I don't recommend that you show a dialog box from deep inside code that isn't supposed to be doing UI. Showing a window, especially a dialog window will interfere with normal message flow in your application. If you want to use a dialog box for this bitmap viewer, then you want that dialog window to be something that the User shows, and that you just draw onto if it's there.
If you don't have access to an HINSTANCE, it's still possible to show a dialog box, it's just more work. That's sort of a different question.
About all you need is a handle to a device context (HDC). To display your data on it:
CreateDibSection to create a DIBSection.
Copy your data to the memory block returned by CreateDibSection.
create a DC compatible with the target DC.
Select the DIBSection into your newly created DC.
BitBlt (or StretchBlt) from your DC to the target DC.
I'm writing an unmanaged Win32 C++ function that gets a handle to a bitmap, and I need to draw on it.
My problem is that to draw I need to get a device context, but when I do GetDC (NULL), it gives me a device context for the WINDOW! The parameter for GetDC () is a window handle (HWND), but I don't have a window; just a bitmap handle.
How can I draw on this bitmap? Thanks!
In addition to Pavel's answer, the "compatible with the screen" always bugged me too, but, since CreateCompatibleDC(NULL) is universally used for that purpose, I assume it is correct.
I think that the "compatible" thing is related just to DDB (the DC is set up to write on the correct DDB type for the current screen), but does not affect read/writes on DIBs.
So, to be safe, always use DIBs and not DDBs if you need to work on bitmaps that doesn't just have to go temporarily onscreen, nowadays the difference in performance is negligible. See here for more info about DIBs and DDBs.
CreateCompatibleDC() and SelectObject() your bitmap into it.
However, not every bitmap can be selected into any DC.
You might have to play with mapping mode and other options of memory DCs.
The basic win32 paradigm for drawing on a bitmap is that you select the bitmap onto a device context, after which, all drawing operations on that device context are stored in the bitmap. You then use one of the various 'blit' operations (e.g. StretchBlt) to transfer this to a display surface, which is just the device context of a window client area.
Others have provided better detail, this is just the high-level view.
Well, this is a bit outside the box.. I guess.. But I do know that Graphics can return a HDC, and Graphics take a Bitmap as an argument to its ctor . A Bitmap in turn can be created from a HBITMAP and a HPALETTE. The only problem here is that I do not know if the HPALETTE argument can be NULL.
Graphics* g;
Bitmap* bitmap;
HBITMAP _bitmap; // <- this one is yours
bitmap = Bitmap::FromHBITMAP(_bitmap, NULL);
g = new Graphics(bitmap);
HDC hdc = g->GetHDC();
// when done, call g->ReleaseHDC(hdc);
However, I would urge you to receive the HDC as an argument to your function as well.. I do not think that anyone will have a BITMAP and NOT have the DC to it.
If you're having these issues with finding a HDC to a HBITMAP, so will everyone else.
Use SelectObject() on your memory DC to select the bitmap into it. This makes me puzzled.
I read the msdn but still don't know how to fill the second parameter of SelectObject().
Call OpenClipbard() to open the clipboard and call GetClipboardData() with a type of CF_BITMAP to get the handle to the image data stored on the clipboard. If there's no image on the clipboard, the NULL handle will be returned.
Then, inside your window's WM_PAINT handler, use BeginPaint() to get a device context for drawing into your window, and use CreateCompatibleDC() to create a memory device context for the bitmap. Use SelectObject() on your memory DC to select the bitmap into it, and finally use BitBlt() to blit the bitmap from the memory DC onto the window's DC. Don't forget to clean up -- call DeleteDC() to delete the memory DC, and call EndPaint() to end drawing.
Lastly, call CloseClipboard() when you're done. Note that the clipboard owns the bitmap handle, and as soon as you call CloseClipboard(), the bitmap will be destroyed. So, if you want to hang onto the bitmap after you've closed the clipboard, you'll need to make a copy of it.