Skip to content

Instantly share code, notes, and snippets.

@wduminy
Last active March 14, 2024 05:17
Show Gist options
  • Save wduminy/5859474 to your computer and use it in GitHub Desktop.
Save wduminy/5859474 to your computer and use it in GitHub Desktop.
Flips a surface in SDL
SDL_Surface* flip_vertical(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);
const auto pitch = sfc->pitch;
const auto pxlength = pitch*(sfc->h - 1);
auto pixels = static_cast<unsigned char*>(sfc->pixels) + pxlength;
auto rpixels = static_cast<unsigned char*>(result->pixels) ;
for(auto line = 0; line < sfc->h; ++line) {
memcpy(rpixels,pixels,pitch);
pixels -= pitch;
rpixels += pitch;
}
return result;
}
@rogerallen
Copy link

rogerallen commented Jun 24, 2019

Almost perfect.

pixels needs to change to start at the begining of the last line of pixels, not one line beyond the last pixel.

changing line 6 to: const auto pxlength = pitch*(sfc->h - 1); works for me

@wduminy
Copy link
Author

wduminy commented Jun 24, 2019

Thanks - I updated line 6 :-)

@abuharth
Copy link

How would I approach doing this operation but for horizontal flipping

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment