【问题标题】:SDL2 texture's pixel format and surface color maskSDL2 纹理的像素格式和表面颜色遮罩
【发布时间】:2026-01-06 18:50:01
【问题描述】:

我正在尝试为像素操作创建一个 SDL_Surface,但是在设置表面的颜色蒙版时确实出现了问题,因为在填充颜色缓冲区时颜色不正确(请参阅 cmets,我正在尝试解释u8vec4 作为 RGBA 颜色):

const int win_width = 640;
const int win_height = 480;
std::vector<glm::u8vec4> colors{ win_width * win_height, glm::u8vec4{ 0, 0, 0, 0 } };

SDL_Surface* render_surface = SDL_CreateRGBSurfaceFrom(&colors[0], win_width, win_height, 32,
    sizeof(glm::u8vec4) * win_width, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);

SDL_Texture* render_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, 
    SDL_TEXTUREACCESS_STREAMING, win_width, win_height);

// { 255, 0, 0, 255 } = Red
// { 255, 0, 0, 100 } = Darker red, alpha seems to be working
// { 0, 255, 0, 255 } = Purple!? Should be green?
// { 0, 0, 255, 255 } = Yellow, expecting blue
std::fill(colors.begin(), colors.end(), glm::u8vec4{ 0, 0, 0, 255 }); // Red
SDL_UpdateTexture(render_texture, nullptr, render_surface->pixels, render_surface->pitch);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, render_texture, nullptr, nullptr);
SDL_RenderPresent(renderer);

【问题讨论】:

  • 从右到左(ABGR)读取颜色值,我可以想象它们会产生您描述的颜色。

标签: c++ sdl sdl-2


【解决方案1】:

您应该尝试根据字节序设置您的位图。这是我的做法:

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    const uint32_t R_MASK = 0xff000000;
    const uint32_t G_MASK = 0x00ff0000;
    const uint32_t B_MASK = 0x0000ff00;
    const uint32_t A_MASK = 0x000000ff;
#else
    const uint32_t R_MASK = 0x000000ff;
    const uint32_t G_MASK = 0x0000ff00;
    const uint32_t B_MASK = 0x00ff0000;
    const uint32_t A_MASK = 0xff000000;
#endif

在你的情况下,你已经得到了相反的颜色掩码。


我认为 Jongware 是正确的,格式是 ABGR。

// { 255, 0, 0, 100 } = Darker red, alpha seems to be working

我猜这里的 alpha 似乎是正确的,因为背景是黑色的,并且通过将红色的数量减少到 100,它会自然地与背景融为一体。

我也觉得你没有设置SDL_BlendMode

【讨论】:

  • 使用 SDL_PIXELFORMAT_ABGR8888,这些掩码(小端序)和 SDL_SetTextureBlendMode(..., SDL_BLENDMODE_BLEND) 使其工作。