gpt4 book ai didi

c++ - 获取 SDL_Texture 中单个像素的 SDL_Color

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:47 37 4
gpt4 key购买 nike

我在寻找有关如何检索 SDL_Texture 上像素的特定颜色的解决方案时遇到了一些问题...更具体一点:我正在尝试计算给定纹理中使用的平均颜色量。稍后我想将红色像素的数量除以像素总数。对于这个任务,我需要一个方法,它会得到每个像素的颜色...

我试图搜索一些函数,但不幸的是我没能弄明白..我看到了像 SDL_RenderReadPixels 和 SDL_GetPixelFormatName 这样的方法,但是这些方法都没有帮助我...

你有什么解决方案吗?

最佳答案

要访问 SDL_Texture 的像素,您必须使用 SDL_CreateTexture() 创建空白纹理并传入 SDL_TEXTUREACCESS_STREAMING 作为访问参数,然后将表面的像素复制到其中。完成后,您可以使用 SDL_LockTexture() 函数检索指向像素数据的指针,然后可以访问和修改该像素数据。要保存您的更改,您需要调用 SDL_UnlockTexture()。尝试这样的事情:

SDL_Texture *t;

int main()
{
// Init SDL

SDL_Surface * img = IMG_Load("path/to/file");
SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, img->w, img->h);

void * pixels;

SDL_LockTexture(t, &img->clip_rect, &pixels, img->pitch);

memcpy(pixels, img->pixels, img->w * img->h);

Uint32 * upixels = (Uint32 *) pixels;

// get or modify pixels

SDL_UnlockTexture(t);

return 0;
}

Uint32 get_pixel_at(Uint32 * pixels, int x, int y, int w)
{
return pixels[y * w + x];
}

您可以像这样从像素中获取颜色:

Uint32 pixel = get_pixel_at(pixels, x, y, img->w);
Uint8 * colors = (Uint8 *) pixel;

// colors[0] is red, 1 is green, 2 is blue, 3 is alpha (assuming you've set the blend mode on the texture to SDL_BLENDMODE_BLEND

如果您想了解更多信息,请查看这些 SDL 2.0 教程:http://lazyfoo.net/tutorials/SDL/index.php .教程 40 专门处理这个问题。

如果您有任何问题或不清楚的地方,请告诉我。

祝你好运!

关于c++ - 获取 SDL_Texture 中单个像素的 SDL_Color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23367098/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com