문제

I am trying to build a very simple graphical app using C++, windows api and GDI+. When first trying to build the app, heavy flickering was introduced, so this code tries to use double buffering, but fails. hdcBuf is the backbuffer.

When trying to draw something to the backbuffer using GDI+ Graphics::DrawCachedBitmap the bitmap is drawn dual-colored in black and white.

LoadBitmapRes creates a CachedBitmap from the EXE resources; this function works with single buffering.

Is there anything wrong in the code? Thanks in advance!

Global:

CachedBitmap* fish;
HDC hdc;
HDC hdcBuf;
HBITMAP hbmpBuf;
Graphics* gfxBuf;

WM_CREATE:

hdc = GetDC(hwnd);
hdcBuf = CreateCompatibleDC(hdc);
hbmpBuf = CreateCompatibleBitmap(hdcBuf, 640, 480);
SelectObject(hdcBuf, hbmpBuf);
gfxBuf = Graphics::FromHDC(hdcBuf); 
fish = LoadBitmapRes(gfxBuf, MAKEINTRESOURCE(FISH2), "SPRITE");

WM_PAINT:

HDC temp = BeginPaint(hwnd, &ps);
gfxBuf->DrawCachedBitmap(fish, x, y);
BitBlt(temp, 0, 0, 640, 480, hdcBuf, 0, 0, SRCCOPY);
EndPaint(hwnd, &ps);
도움이 되었습니까?

해결책

When creating a memory DC using CreateCompatibleDC its display surface is exactly one monochrome pixel wide and one monochrome pixel high. Consequently when calling CreateCompatibleBitmap on this memory DC a monochrome bitmap is created.

Since the bitmap selected into a memory DC controls the color characteristics, you have to make sure that it matches the DC you are eventually using to display the contents of the memory DC. To do so you should pass the destination DC to CreateCompatibleBitmap.

Corrected code:

hdc = GetDC(hwnd);
hdcBuf = CreateCompatibleDC(hdc);
hbmpBuf = CreateCompatibleBitmap(hdc, 640, 480); // uses source DC
SelectObject(hdcBuf, hbmpBuf);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top