Re: [SDL2] Texture with alpha and mouse cursor over it

"Naith" <[email protected]>
Newsgroups gmane.comp.lib.sdl
Message-ID <[email protected]>
It is possible to retrieve the pixels of a SDL_Texture, but it's a costly process and you shouldn't do it. What you should do instead is checking the pixel color of the surface that is created before the texture is created. This means that you'll have to save the SDL_Surface in some way and destroy it when the SDL_Texture is destroyed. One way you can achieve this is by having both the SDL_Surface and the SDL_Texture inside a struct and destroy everything when the program ends.
Example code below:


Code:

struct STexture
{
	SDL_Surface*  pSurface = NULL;
	SDL_Texture*  pTexture = NULL;
	SDL_Rect		Quad;
};

STexture* pMyTexture = NULL;




Then, when the program is executed, check if the mouse pointer is inside the texture quad (see struct above) and if it is, retrieve the pixel color from the surface and then do whatever you want with the pixel information you retrieve.
Example code for retrieving the pixel color of a SDL_Surface:


Code:

SDL_Color GetPixelColor(SDL_Surface* pSurface, const int X, const int Y)
{
	int		Bpp		= pSurface->format->BytesPerPixel;
	Uint8*	pPixel	= (Uint8*)pSurface->pixels + Y * pSurface->pitch + X * Bpp;

	Uint32 PixelColor = *(Uint32*)pPixel;

	SDL_Color Color = {0, 0, 0, 0};

	SDL_GetRGBA(PixelColor, pSurface->format, &Color.r, &Color.g, &Color.b, &Color.a);

	return Color;
}





And example code on how to use it:


Code:

	// Where on the texture the mouse pointer is positioned, relative to the texture quad's upper left corner
	SVector2D Position = {MousePosition.x - pMyTexture->Quad.x, MousePosition.y - pMyTexture->Quad.y};

	const SDL_Color PixelColor = GetPixelColor(pMyTexture->pSurface, (int)Position.x, (int)Position.y);
		
	printf("Pixel alpha: %i\n", PixelColor.a);





Hope it helps :)

_______________________________________________
SDL mailing list
[email protected]
http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.