Sdl Get pixel color
When it comes to per-pixel SDL things, I like this site.
It shows us this code to place a pixel:
From this, we can easily get the color, instead of placing it.
Just change 'ptr[lineoffset + x] = color;' to 'return ptr[lineoffset + x];', and change the function's parameters and return type. (Return type should be type 'Uint32'.
These functions return the color not in a SDL_Color format, but bitshifted into a unsigned 32 bit integer. Look at SDL's documentation on 'SDL_MapRGB' and 'SDL_GetRGB' to figure out how to convert the ints.
Here's LazyFoo's example: (Read this tutorial)
You must lock and unlock your surfaces when accessing the pixels. (I think it's only required when writing new pixels, but I do it when reading and when writing, just to be sure)
Just read this: LazyFoo's SDL Lesson #31
It shows us this code to place a pixel:
void putpixel(int x, int y, int color){ unsigned int *ptr = (unsigned int*)screen->pixels; int lineoffset = y * (screen->pitch / 4); ptr[lineoffset + x] = color;}
From this, we can easily get the color, instead of placing it.
Just change 'ptr[lineoffset + x] = color;' to 'return ptr[lineoffset + x];', and change the function's parameters and return type. (Return type should be type 'Uint32'.
These functions return the color not in a SDL_Color format, but bitshifted into a unsigned 32 bit integer. Look at SDL's documentation on 'SDL_MapRGB' and 'SDL_GetRGB' to figure out how to convert the ints.
Here's LazyFoo's example: (Read this tutorial)
Uint32 get_pixel32( SDL_Surface *surface, int x, int y ){ //Convert the pixels to 32 bit Uint32 *pixels = (Uint32 *)surface->pixels; //Get the requested pixel return pixels[ ( y * surface->w ) + x ];}void put_pixel32( SDL_Surface *surface, int x, int y, Uint32 pixel ){ //Convert the pixels to 32 bit Uint32 *pixels = (Uint32 *)surface->pixels; //Set the pixel pixels[ ( y * surface->w ) + x ] = pixel;}
You must lock and unlock your surfaces when accessing the pixels. (I think it's only required when writing new pixels, but I do it when reading and when writing, just to be sure)
//Lock the surface.if(SDL_MUSTLOCK(mySurface)) SDL_LockSurface(mySurface);//pixel altering code goes here.//Unlock when we are done.if(SDL_MUSTLOCK(mySurface)) SDL_UnlockSurface(mySurface);
Just read this: LazyFoo's SDL Lesson #31
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement