Skip to main content
GameDev.net gamedev.net
🔒 Locked

Sdl Get pixel color

Started by Yamulley Jul 21, 2008 at 11:08 AM 0 replies 25.7k views
Original Post
Yamulley
Yamulley
How can i get a pixel red component number(0 - 255) in SDL surface? int red = ???
Servant of the Lord
Servant of the Lord
When it comes to per-pixel SDL things, I like this site.

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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.