CreateCompatibleDC result has only two colors.

In the following code, at any time when CreateCompatibleDC is called, the resulting device context has only two colors: black and white.

case WM_PAINT: { PAINTSTRUCT ps; ps.hdc=GetDC(g_CSkeletalViewerApp.m_hWnd); ps.fErase=true; RECT rc; GetWindowRect(g_CSkeletalViewerApp.m_hWnd, &rc ); ps.rcPaint=rc; int width = rc.right - rc.left; int height = rc.bottom - rc.top; HDC hdc=BeginPaint(hWnd,&ps); HDC memdc=CreateCompatibleDC(hdc); HBITMAP membm=CreateCompatibleBitmap(memdc,width,height); SelectObject(memdc,membm); for(int i=rc.left; i<rc.right; i++) { for(int j=rc.top; j<rc.bottom; j++) SetPixel(memdc,i,j,RGB((i+j)%255,(i+j)%255,(i+j)%255)); } BitBlt(hdc,0,0,width,height,memdc,0,0,SRCCOPY); DeleteDC(memdc); EndPaint(hWnd,&ps); } break; 

GetDeviceCaps (memdc, SIZEPALETTE) returns 0. The same is true for hdc, so I cannot change the palette manually. The color depth for both device contexts is 32 bits. GetLastError - 0 immediately after CreateCompatibleDC. GetNearestColor (memdc, RGB (any color)) is either black or white. After calling CreateCompatiobleDC in any device context (and not just in hdc), the same problem occurs.

Any ideas?

+4
source share
1 answer

Change this:

 HBITMAP membm=CreateCompatibleBitmap(memdc,width,height); 

For this:

 HBITMAP membm=CreateCompatibleBitmap(hdc,width,height); 

When you create a compatible DC, it is created with a bitmap - but that bitmap is always a 1x1 monochrome bitmap (i.e. one pixel of black or white), regardless of which DC it is compatible with.

As a result, if you create a bitmap compatible with this DC, you will get a larger, single-color bitmap.

If, however, you create a bitmap compatible with the source DC, then you will get a bitmap of the requested size and color depth of the source DC.

+8
source

All Articles