簡體   English   中英

如何從SDL_Surface獲取特定像素的顏色?

[英]How to get the color of a specific pixel from SDL_Surface?

我正在嘗試從SDL_Surface獲取像素的RGB / RGBA顏色。 我在互聯網上找到了此代碼,但返回的數字很奇怪(對於0紅色,0綠色,255藍色的像素,則為67372036)

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 您可以按照該頁面上顯示的內容進行操作,也可以只使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM