Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c++ - The result of CreateCompatibleDC only has two colors

In the following code, anytime CreateCompatibleDC is called, the resulting device context only has 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. Same for hdc, so I can't change the palette manually. The color depth for both device contexts is 32 bits. GetLastError is 0 immediately after CreateCompatibleDC. GetNearestColor(memdc,RGB(any color)) is either black or white. After calling CreateCompatiobleDC on any device context (not just hdc), the same problem occurs.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change this:

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

To this:

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

When you create a compatible DC, it's created with a bitmap--but that bitmap is always a 1x1 monochrome bitmap (i.e., a single pixel that's either black or white), regardless of what sort of DC it's compatible with.

As a result, if you create a bitmap compatible with that DC, you'll get a larger monochrome bitmap.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...