Jump to content
  • Advertisement
Sign in to follow this  
Yamulley

Sdl Get pixel color

This topic is 3626 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

Advertisement
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

Share this post


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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!