Vertically invert a surface in SDL

From HalfgeekKB
Revision as of 18:53, 30 May 2005 by 64.134.50.170 (talk)
Jump to navigation Jump to search

This code flips an SDL_Surface upside-down by using a buffer the size of one line of the image to swap the first and last successively until the middle is reached.

int invert_surface_vertical(SDL_Surface *surface)
{
    /* buffer big enough for one line of this image */
    Uint8 *line;
    Uint8 *a, *b;
    Uint16 pitch;

    if( SDL_MUSTLOCK(surface) ) {
        if( SDL_LockSurface(surface) < 0 ) {
            return -2;
        }
    }

    pitch = surface->pitch * sizeof(Uint8);

    line = (Uint8*)malloc(pitch);

    if( line == NULL )
        return -1;

    /* let us begin swapping the first and last lines
        of an ever-narrowing area of the image */
    a = (Uint8*)surface->pixels;
    b = a + pitch * (surface->h - 1);


    while( a < b ) {
        /* memcpy(dest, src, len) */
        memcpy(line, b, pitch);
        memcpy(b, a, pitch);
        memcpy(a, line, pitch);

        a += pitch;
        b -= pitch;
    }

    free(line);

    if( SDL_MUSTLOCK(surface) ) {
        SDL_UnlockSurface(surface);
    }

    return 1;
}