Advertisement Jump to content
Sign in to follow this  

Sdl Get pixel color

This topic is 3834 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

//pixel altering code goes here.

//Unlock when we are done.

Just read this: LazyFoo's SDL Lesson #31

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!