如何在SDL_surface中设置像素?

nou*_*fal 5 c c++ graphics sdl

我需要从此页面使用以下功能。该SDL_Surface结构被定义为

typedef struct SDL_Surface {
    Uint32 flags;                           /* Read-only */
    SDL_PixelFormat *format;                /* Read-only */
    int w, h;                               /* Read-only */
    Uint16 pitch;                           /* Read-only */
    void *pixels;                           /* Read-write */
    SDL_Rect clip_rect;                     /* Read-only */
    int refcount;                           /* Read-mostly */
} SDL_Surface;
Run Code Online (Sandbox Code Playgroud)

该函数是:

void set_pixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
      Uint8 *target_pixel = (Uint8 *)surface->pixels + y * surface->pitch + x * 4;
      *(Uint32 *)target_pixel = pixel;
}
Run Code Online (Sandbox Code Playgroud)

在这里我几乎没有疑问,可能是由于缺乏真实的画面。

  1. 为什么我们需要乘surface->pitchy,并x通过4
  2. 首先声明,然后将其声明target_pixel为后续8-bit integer pointer,有什么必要32-bit integer pointer
  3. 函数返回后如何target_pixel保留pixelset_pixel

unw*_*ind 8

  1. 由于每个像素的大小为 4(表面正在使用Uint32-valued 像素),但计算是在Uint8. 该4是丑陋的,见下文。
  2. 使地址计算以字节为单位。
  3. 由于要写入的像素实际上是 32 位,因此指针必须是 32 位才能使其成为单次写入。

计算必须以字节为单位,因为表面的pitch字段以字节为单位。

这是一个(没有我最初的尝试那么激进)重写:

void set_pixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
  Uint32 * const target_pixel = (Uint32 *) ((Uint8 *) surface->pixels
                                             + y * surface->pitch
                                             + x * surface->format->BytesPerPixel);
  *target_pixel = pixel;
}
Run Code Online (Sandbox Code Playgroud)

请注意我们如何surface->format->BytesPerPixel用来分解4. 魔术常数不是一个好主意。另请注意,以上假设表面确实使用 32 位像素。

  • 第一:先打'google sdl pitch':“pitch是内存缓冲区的宽度,可以大于表面的宽度。” 雄辩地说,不能改进。第二:是的。(任何其他职位都无济于事......) (2认同)

Sor*_*ian 6

您可以使用以下代码:

unsigned char* pixels = (unsigned char*)surface -> pixels; pixels[4 * (y * surface -> w + x) + c] = 255;

x是您想要的点的 x,是该点y的 y 并c显示您想要的信息:
if c == 0 >>> blue
if c == 1 >>> green
if c == 2 >>> red
if c == 3 >>> alpha(不透明度)

  • surface->w 是错误的,应该使用 surface->pitch,因为可能存在内存对齐填充(通常可被 4 整除)以进行内部内存优化 (2认同)