Bookmark GamesCreators

Google
 
Web Games Creators

 
News
Articles
Forum
Downloads
 
Send your article
Send your demo
Send your game
 
Contact Webmaster

Thanks to:

SourceForge.net Logo

 

 

 

 

Replacing Colors

 

   

 

PutPixel and GetPixel from main.c

void PutPixel(SDL_Surface *surf, int x, int y, Uint32 pixel)
{
   //This function replaces the pixel on x,y position with color: pixel
   int bpp = surf->format->BytesPerPixel;
   Uint8 *p = (Uint8 *)surf->pixels + y * surf->pitch + x*bpp;

   switch (bpp)
   {
      case 1:
         *p = pixel;
      break;

      case 2:
         *(Uint16 *)p = pixel;
      break;

      case 3:
         if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            {
               p[0]=(pixel >> 16) & 0xff;
               p[1]=(pixel >> 8) & 0xff;
               p[2]=pixel & 0xff;
            }
            else
            {
               p[0]=pixel & 0xff;
               p[1]=(pixel >> 8) & 0xff;
               p[2]=(pixel >> 16) & 0xff;
            }
      break;

      case 4:
         *(Uint32 *) p = pixel;
      break;
   }
}




Uint32 GetPixel(SDL_Surface *surf, int x, int y)
{
   //This function returns pixels color
   int bpp = surf->format->BytesPerPixel;
   Uint8 *p = (Uint8 *)surf->pixels + y * surf->pitch + x * bpp;

   switch (bpp)
   {
      case 1:
         return *p;

      case 2:
         return *(Uint16 *)p;

      case 3:
         if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
         else
            return p[0] | p[1] << 8 | p[2] << 16;

      case 4:
         return *(Uint32 *)p;

      default:
         return 0;
   }
}

 

   PutPixel function receives a pointer to SDL_Surface, x and y position of pixel and Uint32 value (color). Then the pixel position is calculated (Read more about SDL_Surface) and this pixel is assigned pixel color. This switch makes some calculations if the surface surf has 8bit, 16bits, 24bits or 32bits per pixel format.

   GetPixel function does almost the same but it reads the pixel's color and returns it. This is the resulting output:

   Any questions, sugestions, comments click here

by Anton Galitch     (gamescreators@gmail.com)     06.07.06

 

Previous