Get pixel info from SDL2 texture

守給你的承諾、 提交于 2019-12-01 10:49:17

You can accomplish this by using Render Targets.

SDL_SetRenderTarget(renderer, target);
... render your textures rotated, flipped, translated using SDL_RenderCopyEx
SDL_RenderReadPixels(renderer, rect, format, pixels, pitch);

With the last step you read the pixels from the render target using SDL_RenderReadPixels and then you have to figure out if the alpha channel of the desired pixel is zero (transparent) or not. You can read just the one pixel you want from the render target, or the whole texture, which option you take depends on the number of hit tests you have to perform, how often the texture is rotated/moved around, etc.

You need to create your texture using the SDL_TEXTUREACCESS_STREAMING flag and lock your texture before being able to manipulate pixel data. To tell if a certain pixel is transparent in a texture make sure that you call

SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);

this allows the texture to recognize an alpha channel.

Try something like this:

SDL_Texture *t;

int main()
{
    // initialize SDL, window, renderer, texture
    int pitch, w, h;
    void *pixels;

    SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);

    SDL_QueryTexture(t, NULL, &aw, &h);
    SDL_LockTexture(t, NULL, &pixels, &pitch);
    Uint32 *upixels = (Uint32*) pixels;

    // you will need to know the color of the pixel even if it's transparent
    Uint32 transparent = SDL_MapRGBA(SDL_GetWindowSurface(window)->format, r, g, b, 0x00);

    // manipulate pixels
    for (int i = 0; i < w * h; i++)
    {
        if (upixels[i] == transparent)
            // do stuff
    }

    // replace the old pixels with the new ones
    memcpy(pixels, upixels, (pitch / 4) * h);

    SDL_UnlockTexture(t);

    return 0;
}

If you have any questions please feel free to ask. Although I am no expert on this topic.

For further reading and tutorials, check out http://lazyfoo.net/tutorials/SDL/index.php. Tutorial 40 deals with pixel manipulation specifically.

I apologize if there are any errors in method names (I wrote this off the top of my head).

Hope this helped.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!