如何在C ++中将位图绘制为OpenGL纹理?

时间:2011-09-04 09:48:51

标签: c++ winapi opengl bitmap textures

我有一个位图及其句柄(Win32 HBITMAP)。有关如何在OpenGL四边形上绘制此位图的任何建议(通过缩放和拉动位图的4个角来适应四边形的4个顶点)?

2 个答案:

答案 0 :(得分:5)

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

创建纹理后,您可以像平常一样应用此方法(启用纹理,为四边形的每个角设置一个纹理坐标)。

由于评论而编辑

这个(未经测试的!)代码应该可以解决问题

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;
}

答案 1 :(得分:2)

问题有点宽泛:要准确回答,人们必须描述整个OpenGL的工作原理。但是仍然没有什么比你想要的更难,只是看看 通过一些教程,如下:

http://www.nullterminator.net/gltexture.html
http://www.cityintherain.com/howtotex.html

此外,这可能有助于改善低调:http://www.opengl.org/wiki/Texture