[SDL] quick flip an image

Sebastian Beschke s.beschke at gmx.de
Wed Jan 5 12:40:06 PST 2005


Hi,

There's been a lot of discussion about the pros and cons of image 
flipping and whatnot in this thread, and to be honest I haven't read all 
of it, but the truth is that mirroring images is useful in a lot of 
simple games. Since I've just written some code to do this, I might as 
well post it here.

One catch: It's in D, but the differences to C shouldn't be so great. 
Basically, replace the . with ->, replace uint with Uint32 and ubyte 
with Uint8. And one line contains the copy of an array slice, which 
would need to be reimplemented with memcpy in C.

The actual point is to show the principle; if you know the principle of 
it, reimplementing it should be easy.

By the way, it doesn't matter if it's slow, because it should be done at 
load time anyway (or at the time it's first requested, but *not* at 
every draw).


SDL_Surface* hmirror(SDL_Surface* sfc)
{
     SDL_Surface* result = SDL_CreateRGBSurface(sfc.flags, sfc.w, sfc.h,
         sfc.format.BytesPerPixel * 8, sfc.format.Rmask, sfc.format.Gmask,
         sfc.format.Bmask, sfc.format.Amask);
     ubyte* pixels = cast(ubyte*) sfc.pixels;
     ubyte* rpixels = cast(ubyte*) result.pixels;
     uint pitch = sfc.pitch;
     uint pxlength = pitch*sfc.h;
     uint bypp = sfc.format.BytesPerPixel;
     assert(result != null);

     for(uint col = 0; col < pitch; col += bypp) {
         for(uint line = 0; line < sfc.h; ++line) {
             uint rpos = line * pitch + col;
             uint pos = line * pitch + (pitch - col - bypp);
             rpixels[rpos..rpos+bypp] = pixels[pos..pos+bypp];
         }
     }

     return result;
}


Here's another one for vertical (upside-down) mirroring:


SDL_Surface* flipVert(SDL_Surface* sfc)
{
     SDL_Surface* result = SDL_CreateRGBSurface(sfc.flags, sfc.w, sfc.h,
         sfc.format.BytesPerPixel * 8, sfc.format.Rmask, sfc.format.Gmask,
         sfc.format.Bmask, sfc.format.Amask);
     ubyte* pixels = cast(ubyte*) sfc.pixels;
     ubyte* rpixels = cast(ubyte*) result.pixels;
     uint pitch = sfc.pitch;
     uint pxlength = pitch*sfc.h;
     assert(result != null);

     for(uint line = 0; line < sfc.h; ++line) {
         uint pos = line * pitch;
         rpixels[pos..pos+pitch] = 
pixels[(pxlength-pos)-pitch..pxlength-pos];
     }

     return result;
}


Sebastian



Serjan Pruis schrieb:
> Hello I was wondering if it is possible to quick flip an image.
> I do mean if i have a bitmap of a person looking to the right and i want 
> him to look to the left.
> Can i do that quick and easy? Or is the only way to do that quick having 
> two images (left and right looking guy)?
> 
> 
> 
> _______________________________________________
> SDL mailing list
> SDL at libsdl.org
> http://www.libsdl.org/mailman/listinfo/sdl
> 
> 




More information about the SDL mailing list