如何使用 SDL2 读取像素颜色?

How to read pixel colors using SDL2?

我想加载一个 png 图像,并获取其中一些像素的颜色(32 位 RGBA 格式)。我已经搜索了很多,但还没有找到一个好的工作解决方案。

我发现的是使用 SDL_LockTexture 的像素操作。但是不想改变图像,只读取它的一些像素。

因为你没有指定,我假设你正在使用 SDL_image to load images. Therefore IMG_Load 是一个很好的讨论对象。
正如您从 link 中看到的那样,它 returns 一个 SDL_Surface(您可能希望将其转换为纹理,但您不需要这样做来读取其像素).
对于这样的对象,您可以使用:

*SDL_LockSurface:

Use this function to set up a surface for directly accessing the pixels.

*SDL_UnlockSurface:

Use this function to release a surface after directly accessing the pixels.

文档还指出:

Between calls to SDL_LockSurface() / SDL_UnlockSurface(), you can write to and read from surface->pixels, using the pixel format stored in surface->format.

像素和格式都由您支配。看起来是个不错的人选,可以满足您的要求。


但是...

I would like to load a png image, [...]

请注意 IMG_LoadPNG_RW returns 一个 SDL_Surface 以及 IMG_Load.