c++ - 如何使用 SDL 修改像素?

标签 c++ sdl

我有一个小问题:我无法修改 SDL 屏幕的像素。

具体来说,以下代码不起作用。

Uint32 * pixels = (Uint32 *) screen -> pixels; 
screen -> pixels = pixels;

这会编译,但不会显示任何内容。我错过了什么?

最佳答案

我有以下函数用于在 SDL_Surface 中设置像素。有两个版本,分别用于 32 位、24 位、16 位和 8 位表面。如果您只想设置单个像素,则可以使用普通版本。但是如果你想设置一堆像素,首先你锁定表面,然后你使用 nolock 版本(之所以这样命名是因为它不锁定表面),然后你解锁。这样你就不会重复锁定和解锁表面,这应该是一项昂贵的操作,但我认为我从未真正测试过它。

void PutPixel32_nolock(SDL_Surface * surface, int x, int y, Uint32 color)
{
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint32));
    *((Uint32*)pixel) = color;
}

void PutPixel24_nolock(SDL_Surface * surface, int x, int y, Uint32 color)
{
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint8) * 3);
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    pixel[0] = (color >> 24) & 0xFF;
    pixel[1] = (color >> 16) & 0xFF;
    pixel[2] = (color >> 8) & 0xFF;
#else
    pixel[0] = color & 0xFF;
    pixel[1] = (color >> 8) & 0xFF;
    pixel[2] = (color >> 16) & 0xFF;
#endif
}

void PutPixel16_nolock(SDL_Surface * surface, int x, int y, Uint32 color)
{
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint16));
    *((Uint16*)pixel) = color & 0xFFFF;
}

void PutPixel8_nolock(SDL_Surface * surface, int x, int y, Uint32 color)
{
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint8));
    *pixel = color & 0xFF;
}

void PutPixel32(SDL_Surface * surface, int x, int y, Uint32 color)
{
    if( SDL_MUSTLOCK(surface) )
        SDL_LockSurface(surface);
    PutPixel32_nolock(surface, x, y, color);
    if( SDL_MUSTLOCK(surface) )
        SDL_UnlockSurface(surface);
}

void PutPixel24(SDL_Surface * surface, int x, int y, Uint32 color)
{
    if( SDL_MUSTLOCK(surface) )
        SDL_LockSurface(surface);
    PutPixel24_nolock(surface, x, y, color);
    if( SDL_MUSTLOCK(surface) )
        SDL_LockSurface(surface);
}

void PutPixel16(SDL_Surface * surface, int x, int y, Uint32 color)
{
    if( SDL_MUSTLOCK(surface) )
        SDL_LockSurface(surface);
    PutPixel16_nolock(surface, x, y, color);
    if( SDL_MUSTLOCK(surface) )
        SDL_UnlockSurface(surface);
}

void PutPixel8(SDL_Surface * surface, int x, int y, Uint32 color)
{
    if( SDL_MUSTLOCK(surface) )
        SDL_LockSurface(surface);
    PutPixel8_nolock(surface, x, y, color);
    if( SDL_MUSTLOCK(surface) )
        SDL_UnlockSurface(surface);
}

关于c++ - 如何使用 SDL 修改像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6852055/

相关文章:

c++ - 如何设置一个简单的 CGAL + Qt 程序

c++ - 为什么 DECLARE_DYNAMIC 和 IMPLEMENT_DYNAMIC 对 DYNAMIC_DOWNCAST 是必要的?

c++ - 为什么不使用只读 [] 运算符?

c++ - 将 openGL 上下文保存为视频输出

C++ 游戏循环示例

c++ - OpenGL 4.0 Shading Language Cookbook 中的第一个示例

macos - 使用 Haskell 在 OS X 上编译 SDL 失败

opengl - SDL 坐标系,从 (0,0) 到 (w,h) 或 (w-1, h-1)?

android - SDL 一直无法在 Android 上找到字体

c++ - 我不知道结构体和指针的用法