Vertically invert a surface in SDL

From HalfgeekKB
Revision as of 17:20, 30 May 2005 by 64.134.50.170 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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;

    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(line, b, pitch);
        memcpy(b, a, pitch);
        memcpy(a, line, pitch);

        a += pitch;
        b -= pitch;
    }

    free(line);

    return 1;
}