如何在c++中绘制位图作为OpenGL纹理

How to draw bitmap as OpenGL texture in C++?

本文关键字:OpenGL 纹理 位图 绘制 c++      更新时间:2023-10-16

我有一个位图,它的句柄(Win32 HBITMAP)。任何关于如何在OpenGL四边形上绘制此位图的建议(缩放和拉位图的4个角以适合四边形的4个顶点)?

您需要检索HBITMAP中包含的数据,参见http://msdn.microsoft.com/en-us/library/dd144879(v=vs.85).aspx然后您可以使用glTexImage2DglTexSubImage2D

将DIB数据上传到OpenGL

创建纹理后,您可以像往常一样应用此操作(启用纹理,给四边形的每个角一个纹理坐标)。

由于注释而编辑

这段(未经测试的!)代码应该能达到

的效果
GLuint load_bitmap_to_texture(
    HDC device_context, 
    HBITMAP bitmap_handle, 
    bool flip_image) /* untested */
{
    const int BytesPerPixel = sizeof(DWORD);
    SIZE bitmap_size;
    if( !GetBitmapDimensionEx(bitmap_handle, &bitmap_size) )
        return 0;
    ssize_t bitmap_buffer_size = bitmap_size.cx * bitmap_size.cy * BytesPerPixel;
#ifdef USE_DWORD
    DWORD *bitmap_buffer;
#else
    void *bitmap_buffer;
#endif
    bitmap_buffer = malloc(bitmap_buffer_size);
    if( !bitmap_buffer )
        return 0;

    BITMAPINFO bitmap_info;
    memset(&bitmap_info, 0, sizeof(bitmap_info));
    bitmap_info.bmiHeader.biSize = sizeof(bitmap_info.bmiHeader);
    bitmap_info.bmiHeader.biWidth  = bitmap_size.cx;
    bitmap_info.bmiHeader.biHeight = bitmap_size.cy;
    bitmap_info.bmiHeader.biPlanes = 1;
    bitmap_info.bmiHeader.biBitCount = BitsPerPixel;
    bitmap_info.bmiHeader.biCompression = BI_RGB;
    if( flip_image ) /* this tells Windows where to set the origin (top or bottom) */
        bitmap_info.bmiHeader.biHeight *= -1;
    if( !GetDIBits(device_context, 
                   bitmap_handle, 
                   0, bitmap_size.cy, 
                   bitmap_buffer, 
                   &bitmap_info,
                   DIB_RGB_COLORS /* irrelevant, but GetDIBits expects a valid value */ )
     ) {
        free(bitmap_buffer);
        return 0;
    }
    GLuint texture_name;
    glGenTextures(1, &texture_name);
    glBindTexture(GL_TEXTURE_2D, texture_name);
    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
    glPixelStorei(GL_UNPACK_LSB_FIRST,  GL_TRUE);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 bitmap_size.cx, bitmap_size.cy, 0,
                 GL_RGBA,
#ifdef USE_DWORD
                 GL_UNSIGNED_INT_8_8_8_8,
#else
                 GL_UNSIGNED_BYTE, 
#endif
                 bitmap_buffer);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    free(bitmap_buffer);
    return texture_name;
}