如何在SDL2中排列像素?

时间:2018-01-02 17:30:17

标签: c++ sdl-2

我有2x2图像

不应该像这样排列像素吗?

1 2 // each number is a pixel
3 4

我无法使用x和y访问像素,因为 当x = 1且y = 0时,我得到索引2,但打印像素4的rgb值

所以它就像?

1 2 // each number is a pixel
4 3

这是我使用的代码

index = y + x * s->w;
c = s->format->palette->colors[index]; // c is an SDL_Color and s is an SDL_Surface*

我也使用这个for循环并仍然打印相同的

for (Uint8 i = *(Uint8 *)s->pixels; i < s->w*s->h; i++) {
    c = s->format->palette->colors[i];
    printf("%u %u %u %u \n", i, c.r , c.g , c.b);
}

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 */

    /* clipping information */
    SDL_Rect clip_rect;                     /* Read-only */

    /* Reference count -- used when freeing surface */
    int refcount;                           /* Read-mostly */

/* This structure also contains private fields not shown here */
} SDL_Surface;

1 个答案:

答案 0 :(得分:0)

Uint8 *pixel = (Uint8 *)s->pixels,*index;
index = &pixel[y + x * s->pitch];
c = s->format->palette->colors[*index];

使用@ holyblackcat的建议。