Search code examples
graphicssdlblit

How do I keep the original shape of the destination surface when blitting?


Take a look at the screenshot below. There are three thin SDL 2.0 surfaces displayed, all more or less rectangular.

Blitting image 1 onto image 2 - get image 3

The first surface (the brownish paper one) is Image 1 The white one below it with the two corners missing is Image 2

I would like to perform a SDL_BlitSurface so that Image 1 is blitted onto Image 2, but with the shape of Image 2 (in other words, the end result should look like brown paper, but have two of its corners missing.

To do this, I try:

SDL_BlitSurface(Image1, NULL, Image2, NULL);

But instead of the desired result, I get the third surface in the picture (Image 3), which is the same as Image 1


UPDATE


So on keltar's advice, I've replaced my blit function call with a call to a bespoke function that I hope is copying the alpha channel for each pixel from Image 1 to Image 2

copy_alpha(Image1, Image2);
void IMAGETOOL::copy_alpha(SDL_Surface * src, SDL_Surface * dst)
{
    int w = src->w,
        h = src->h;

    Uint32 opixel, npixel;
    Uint8 r, g, b, a;

    if (SDL_MUSTLOCK(src)) SDL_LockSurface(src);
    if (SDL_MUSTLOCK(dst)) SDL_LockSurface(dst);

    Uint8 srcAlpha = 0;
    for (int y = 0; y < h; y++)
        for (int x = 0; x < w; x++)
        {
            opixel = get_pixel(src, x, y);
            SDL_GetRGBA(opixel, src->format, &r, &g, &b, &a);
            srcAlpha = a;
            opixel = get_pixel(dst, x, y);
            SDL_GetRGBA(opixel, dst->format, &r, &g, &b, &a);
            a = srcAlpha;
            npixel = SDL_MapRGBA(dst->format, r, g, b, a);
            put_pixel(dst, x, y, npixel);
        }

    if (SDL_MUSTLOCK(src)) SDL_UnlockSurface(src);
    if (SDL_MUSTLOCK(dst)) SDL_UnlockSurface(dst);
}

The resulting surface has changed. but not in the way I had hoped.

Copying alpha from image 1 to image 2 - get image 3

Not sure what to make of this - any ideas?


Solution

  • Problem solved. In my last update, I was trying to copy alpha from Image 1 to Image 2 - wrong way round!

    But when I use the same function to copy alpha from image 2 to Image 1 (I'm guessing that is what keltar meant for me to do).

    copy_alpha(Image2, Image1);
    

    the modified Image 1 gives the desired result.

    Copying alpha from image 2 to image 1 - get image 3

    Thanks for your help keltar!