【问题标题】:Loading/rendering bitmap issue using winapi使用 winapi 加载/渲染位图问题
【发布时间】:2020-09-22 11:39:59
【问题描述】:

我正在使用 Windows API 将像素直接绘制到屏幕上(使用 CPU,而不是 GPU),并且在加载位图或渲染位图的方式上遇到了问题。以下是相关代码(render_bmp 函数接受参数“buffer”,它是指向 win32_offscreen_buffer 的指针,这是显示在窗口中的全局缓冲区)

这是图像在我的程序中的截图:

这里是源位图:

注意:如果您安装了 user32.lib 和 gdi32.lib,则使用以下命令在 Windows 上使用 cl 编译器进行编译:

cl -FC -Zi C:\stuff\reproduce.cpp user32.lib gdi32.lib

这是重现问题所需的最少代码。您需要将 WinMain 中的 char *filename 分配替换为您机器上 .bmp 的任何路径才能重现。

#include <windows.h>

struct win32_offscreen_buffer {
    BITMAPINFO info;
    void *memory;
    int width;
    int height;
    int bytes_per_pixel;
    int pitch;
};

struct window_dimension {
    int width;
    int height;
};

struct read_file_result {
    unsigned int contents_size;
    void *contents;
};

struct bitmap_result {
    BITMAPFILEHEADER *file_header;
    BITMAPINFOHEADER *info_header;
    unsigned int *pixels;
    unsigned int stride;
};

win32_offscreen_buffer global_buffer;
unsigned char should_quit = 0;  // BOOL

window_dimension get_window_dimension(HWND window) {
    RECT client_rect;
    GetClientRect(window, &client_rect);
    
    window_dimension result;
    
    result.width = client_rect.right - client_rect.left;
    result.height = client_rect.bottom - client_rect.top;
    
    return result;
}

void resize_dib_section(win32_offscreen_buffer* buffer, int width, int height) {
    if (buffer->memory) {
        VirtualFree(buffer->memory, 0, MEM_RELEASE);
    }
    
    int bytes_per_pixel = 4;
    
    buffer->width = width;
    buffer->height = height;
    
    buffer->info.bmiHeader.biSize = sizeof(buffer->info.bmiHeader);
    buffer->info.bmiHeader.biWidth = buffer->width;
    buffer->info.bmiHeader.biHeight = -buffer->height;
    buffer->info.bmiHeader.biPlanes = 1;
    buffer->info.bmiHeader.biBitCount = 32;
    buffer->info.bmiHeader.biCompression = BI_RGB;
    
    int bitmap_memory_size = (buffer->width * buffer->height) * bytes_per_pixel;
    buffer->memory = VirtualAlloc(0, bitmap_memory_size, MEM_COMMIT, PAGE_READWRITE);
    
    buffer->pitch = buffer->width * bytes_per_pixel;
    buffer->bytes_per_pixel = bytes_per_pixel;
}

void display_buffer_in_window(HDC device_context, window_dimension dimension) {
    StretchDIBits(device_context,
                  0, 0, dimension.width, dimension.height,
                  0, 0, global_buffer.width, global_buffer.height,
                  global_buffer.memory,
                  &global_buffer.info,
                  DIB_RGB_COLORS, SRCCOPY);
}

void free_file_memory(void *memory) {
    if (memory) {
        VirtualFree(memory, 0, MEM_RELEASE);
    }
}

read_file_result read_entire_file(LPCSTR filename) {
    read_file_result result = {};
    
    HANDLE file_handle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    
    if (file_handle != INVALID_HANDLE_VALUE) {
        LARGE_INTEGER file_size;
        if(GetFileSizeEx(file_handle, &file_size)) {
            unsigned int file_size32 = file_size.QuadPart;
            result.contents = VirtualAlloc(0, file_size32, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
            
            if (result.contents) {
                DWORD bytes_read;
                if (ReadFile(file_handle, result.contents, file_size32, &bytes_read, 0) && (file_size32 == bytes_read)) {
                    // File read successfully.
                    result.contents_size = file_size32;
                } else {
                    // TODO: Logging
                    free_file_memory(result.contents);
                    result.contents = 0;
                }
            } else {
                // TODO: Logging
            }
        } else {
            // TODO: Logging
        }
        
        CloseHandle(file_handle);
    } else {
        // TODO: Logging
    }
    
    return result;
}

bitmap_result debug_load_bitmap(char* filename) {
    bitmap_result bmp_result = {};

    read_file_result file_result = read_entire_file(filename);
    unsigned char *contents = (unsigned char *)file_result.contents;

    bmp_result.file_header = (BITMAPFILEHEADER *)contents;
    bmp_result.info_header = (BITMAPINFOHEADER *)(contents + 14);
    bmp_result.pixels = (unsigned int *)(contents + bmp_result.file_header->bfOffBits);
    bmp_result.stride = ((((bmp_result.info_header->biWidth * bmp_result.info_header->biBitCount) + 31) & ~31) >> 3);

    return bmp_result;
}

void render_bmp(int x_pos, int y_pos, win32_offscreen_buffer *buffer, bitmap_result bmp) {
    int width = bmp.info_header->biWidth;
    int height = bmp.info_header->biHeight;

    unsigned char* dest_row = (unsigned char*)buffer->memory + (y_pos * buffer->pitch + x_pos);

    // NOTE: Doing this calculation on the source row because the bitmaps are bottom up,
    // whereas the window is top-down. So must start at the bottom of the source bitmap,
    // working left to right.
    unsigned char* source_row = (unsigned char*)(bmp.pixels + ((bmp.stride / 4) * (height - 1)));

    for (int y = y_pos; y < y_pos + height; y++) {
        unsigned int* dest = (unsigned int*)dest_row;
        unsigned int* source = (unsigned int*)source_row;

        for (int x = x_pos; x < x_pos + width; x++) {
            *dest = *source;
            dest++;
            source++;
        }

        dest_row += buffer->pitch;
        source_row -= bmp.stride;
    }
}

LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w_param, LPARAM l_param) {
    LRESULT result = 0;

    switch (message) {
        break;
        case WM_SIZE: {
            window_dimension dim = get_window_dimension(window);
            resize_dib_section(&global_buffer, dim.width, dim.height);
        }
        break;

        case WM_CLOSE: {
            OutputDebugStringA("WM_CLOSE\n");
            should_quit = 1;
        }
        break;

        case WM_ACTIVATEAPP: {
            OutputDebugStringA("WM_ACTIVATEAPP\n");
        }
        break;

        case WM_DESTROY: {
            OutputDebugStringA("WM_DESTROY\n");
        }
        break;

        case WM_PAINT: {
            PAINTSTRUCT paint;
            HDC device_context = BeginPaint(window, &paint);
            
            window_dimension dimension = get_window_dimension(window);
            display_buffer_in_window(device_context, dimension);
            
            OutputDebugStringA("WM_PAINT\n");

            EndPaint(window, &paint);
        }
        break;

        default: {
            result = DefWindowProc(window, message, w_param, l_param);
        }
        break;
    }

    return result;
}

int CALLBACK WinMain(HINSTANCE instance, HINSTANCE prev_instance, LPSTR command_line, int show_code) {
    WNDCLASS window_class = {};

    window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    window_class.lpfnWndProc = window_proc;
    window_class.hInstance = instance;
    window_class.lpszClassName = "PokerWindowClass";
    
    if (RegisterClassA(&window_class)) {
        HWND window_handle = CreateWindowExA(0, window_class.lpszClassName, "Poker",
                                      WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
                                      CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, instance, 0);

        if (window_handle) {
            HDC device_context = GetDC(window_handle);
            
            window_dimension dim = get_window_dimension(window_handle);
            resize_dib_section(&global_buffer, dim.width, dim.height);
            
            char *filename = "c:/stuff/Sierpinski.bmp";
            bitmap_result img = debug_load_bitmap(filename);
            
            // MESSAGE LOOP
            while (!should_quit) {
                MSG msg;
                
                while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
                    if (msg.message == WM_QUIT) {
                        should_quit = 1;
                    }
                    
                    TranslateMessage(&msg);
                    DispatchMessageA(&msg);
                }
                
                render_bmp(0, 0, &global_buffer, img);
                
                window_dimension dimension = get_window_dimension(window_handle);
                display_buffer_in_window(device_context, dimension);
            }
        } else {
            OutputDebugStringA("ERROR: Unable to create window.");
        }
    } else {
        OutputDebugStringA("ERROR: Unable to register the window class.");
    }
}

请注意,源位图的 biBitCount 为 24,而屏幕外缓冲区位图的 biBitCount 为 32。

【问题讨论】:

  • 无关:#include "poker.cpp" 可能是个坏主意。由于您似乎有一个可执行程序,它今天并没有对您产生影响,但包含 .cpp 文件可能会以多种不同方式破坏构建。有关该主题的更多信息,请参见 Why should I not include cpp files and instead use a header?
  • 代码太多了,你应该尝试做一个最小的例子。副手我猜你没有使用RGB位图,你使用的是调色位图。哎呀没关系,最后的屏幕截图验证它是 24 位的。
  • @MarkRansom 我删除了一堆我认为无关紧要的代码。任何想法/可能的调查途径?我被难住了。
  • @JacksonLenhart 这不是一个完整且可重复的样本。 safe_truncate_uint64global_buffer 定义丢失。您能否展示如何重现此问题?
  • @RitaHan-MSFT 我编辑了safe_truncate_uint64global_buffer 的定义。但是它仍然不完整,如果您想尝试重现该问题,将不胜感激,这里是 github 上的存储库(它很小):github.com/jackson-lenhart/native_poker

标签: c++ winapi bitmap


【解决方案1】:

对于绘制位图,有更简单的方法。您不必自己解析 .bmp 文件。给下两个样例你可以试一试。

第一种使用LoadImage函数的方法。参考"How to draw image on a window?"

case WM_CREATE:
{
    hBitmap = (HBITMAP)LoadImage(hInst, L"C:\\projects\\native_poker\\card-BMPs\\c08.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
break;
case WM_PAINT:
{
    PAINTSTRUCT     ps;
    HDC             hdc;
    BITMAP          bitmap;
    HDC             hdcMem;
    HGDIOBJ         oldBitmap;

    hdc = BeginPaint(hWnd, &ps);

    hdcMem = CreateCompatibleDC(hdc);
    oldBitmap = SelectObject(hdcMem, hBitmap);

    GetObject(hBitmap, sizeof(bitmap), &bitmap);
    BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);

    SelectObject(hdcMem, oldBitmap);
    DeleteDC(hdcMem);

    EndPaint(hWnd, &ps);
}
break;

第二种使用GDI+的方法。参考"Loading and Displaying Bitmaps"

#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")

//...

VOID OnPaint(HDC hdc)
{
    Graphics graphics(hdc);
    Image *image = Image::FromFile(L"C:\\projects\\native_poker\\card-BMPs\\c08.bmp");
    graphics.DrawImage(image, 10, 10);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        OnPaint(hdc);
        EndPaint(hWnd, &ps);
    }
    break;

//...

}

【讨论】:

  • 我正在做一个 DIY 方法,这样我就可以完全控制资产加载和渲染代码,而不是使用 Windows 库函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2012-04-07
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多