无法读取(和比较)SDL2中的像素

时间:2014-01-12 18:51:03

标签: sdl pixels

我正在加载SDL2中的PNG文件,我正在尝试在spritesheet动画期间找到要跟踪的“特殊”像素颜色。我已将这些像素放入我的图像中,但我的代码却找不到它们。

我正在使用此代码读取像素(取自互联网,包装到我自己的Texture类中):

Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
int bpp = surface->format->BytesPerPixel;
/* Here p is the address to the pixel we want to retrieve */
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

switch(bpp) {
case 1:
    return *p;
    break;

case 2:
    return *(Uint16 *)p;
    break;

case 3:
    if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
        return p[0] << 16 | p[1] << 8 | p[2];
    else
        return p[0] | p[1] << 8 | p[2] << 16;
    break;

case 4:
    return *(Uint32 *)p;
    break;

default:
    return 0;       /* shouldn't happen, but avoids warnings */
}
}

这些是我用于将像素与我之前设置的“特殊”值进行比较的重要代码:

        // convert special SDL_Color to Uint32
        Uint32 spec1 = SDL_MapRGBA(_texture->GetSDLSurface()->format, _spec1.r, _spec1.g, _spec1.b, 255);
        Uint32 spec2 = SDL_MapRGBA(_texture->GetSDLSurface()->format, _spec2.r, _spec2.g, _spec2.b, 255);

...并且,循环遍历每个精灵帧中的所有像素......

                    // get pixel at (x, y)
                    Uint32 pix = _texture->GetPixel(x, y);

                    // if pixel is a special value, store it in animation
                    if (pix == spec1)
                    {
                        SDL_Point pt = {x, y};
                        anim->Special1.push_back(pt);
                        found1 = true;
                    }
                    else if (pix == spec2)
                    {
                        SDL_Point pt = {x, y};
                        anim->Special2.push_back(pt);
                        found2 = true;
                    }

现在,我在这些if语句中设置一个断点来检查是否找到了颜色,但是从未到达断点。有谁知道问题是什么?

P.S。我也试过使用SDL_MapRGB(),但这也不起作用。

[编辑]

好的,所以我尝试将一个像素放在整个图像的0,0处,RGB值为66,77和88.它将它们读成84,96和107,所以显然颜色要么被改变要么没被读入正常。但是,当我尝试使用特定的alpha值时,它会完美地读取它。我会将我的系统更改为仅使用alpha值,但是当我放入像素并将其与图像的其余部分混合时,我正在使用的像素编辑器会删除alpha值。

1 个答案:

答案 0 :(得分:1)

你的偏移公式不正确,应该是:

Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x

x不需要乘以bpp

来自docs

间距 表面扫描线的长度,以字节为单位

音高,也称为步幅计算如下:

pitch = width * bytes per pixel

bytes per pixel = (bits per pixel + 7) / 8

当您处于正确的字节偏移量时,从中获取Uint32(对于32bpp图像)并进行比较。

相关问题