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

时间:2018-10-31 15:51:36

标签: c++ sdl

我尝试使用此功能设置像素的颜色:

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返回了Uint32。我应该将SDL_Surface转换为每个像素32位,还是可以将Uint32像素转换为24位?

1 个答案:

答案 0 :(得分:2)

您最终将需要屏蔽Uint32pixel个字节中的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)

相关问题