如何在 24 位 SDL_Surface 上设置像素的颜色?

How to set the color of pixel on 24 bit SDL_Surface?

我尝试使用此函数设置像素的颜色:

void set_pixel(SDL_Surface *surface, SDL_Color, int x, int y)
{
    Uint32 pixel= SDL_MapRGB(surface->format, color.r, color.g, color.b);
    Uint32 *target_pixel = (Uint8 *) surface->pixels + y * surface->pitch +
                                                 x * sizeof *target_pixel;
    *target_pixel = pixel;
}

不幸的是它不起作用,我想这是因为我的 SDL_Surface 每个像素有 24 位,但 SDL_MapRGB returns 是一个 Uint32。我应该将我的 SDL_Surface 转换为每像素 32 位,还是有办法将 Uint32 像素转换为 24 位?

您最终需要屏蔽 pixel 中的 Uint32 字节中的 3 个,同时保持 target_pixel 的第 4 个字节不变(记住字节顺序)。

像这样的东西应该很接近,但不考虑字节顺序:

//assumes pixel has 0x00 for unused byte and assumes LSB is the unused byte
*target_pixel = pixel | (*target_pixel & 0xff)

顺便说一下,您的 target_pixel 计算似乎有误。您应该乘以每个像素的字节数,而不是 sizeof(Uint32).