如何从 SDL_Surface 中获取特定像素的颜色?
How to get the color of a specific pixel from SDL_Surface?
我正在尝试从 SDL_Surface 获取像素的 RGB/RGBA 颜色。我在互联网上找到了这段代码,但它 returns 奇怪的数字(67372036 代表 0 红色、0 绿色、255 蓝色的像素)
Uint32 get_pixel32(SDL_Surface *surface, int x, int y)
{
Uint32 *pixels = (Uint32 *)surface->pixels;
return pixels[(y * surface->w) + x];
}
这是我一直在使用的代码:
Uint32 data = get_pixel32(gSurface, 0, 0);
printf("%i", data);
我不确定我的像素是否具有 32 位格式,但其他图片也无法正常工作。
这取决于表面的颜色格式,或SDL_PixelFormat
. You can follow what is presented on that page, or just use SDL_GetRGB
。
找到这段代码并且它工作正常。
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 */
}
}
SDL_Color rgb;
Uint32 data = getpixel(gSurface, 200, 200);
SDL_GetRGB(data, gSurface->format, &rgb.r, &rgb.g, &rgb.b);
我正在尝试从 SDL_Surface 获取像素的 RGB/RGBA 颜色。我在互联网上找到了这段代码,但它 returns 奇怪的数字(67372036 代表 0 红色、0 绿色、255 蓝色的像素)
Uint32 get_pixel32(SDL_Surface *surface, int x, int y)
{
Uint32 *pixels = (Uint32 *)surface->pixels;
return pixels[(y * surface->w) + x];
}
这是我一直在使用的代码:
Uint32 data = get_pixel32(gSurface, 0, 0);
printf("%i", data);
我不确定我的像素是否具有 32 位格式,但其他图片也无法正常工作。
这取决于表面的颜色格式,或SDL_PixelFormat
. You can follow what is presented on that page, or just use SDL_GetRGB
。
找到这段代码并且它工作正常。
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 */
}
}
SDL_Color rgb;
Uint32 data = getpixel(gSurface, 200, 200);
SDL_GetRGB(data, gSurface->format, &rgb.r, &rgb.g, &rgb.b);