PDA

Click to See Complete Forum and Search --> : Transparent


Technocrat
Feb 12th, 2001, 04:17 PM
Anyone have a copy of, or know where I can get, some source code to create a transparent background of a bitmap using DCs and BitBlt?

Thanks

Vlatko
Feb 13th, 2001, 01:19 PM
Try This:

3.3.3. How do I make an image transparent? (build-time)
Contributor: theForger
You need 2 images. A colour image that has black where you want it to be transparent. It's okay to have black elsewhere too, where you don't want transparent. Next you need a monochrome(black and white) image that has white where you want transparent and black everywhere else.

Assuming these are stored as resources....

HBITMAP hbmColour, hbmMask;
hbmColour = LoadBitmap(hInstance, "COLOR");
hbmMask = LoadBitmap(hInstance, "MASK");

Next, once you've got your window and memory DC's (see prev examples) you need to do two BitBlt()'s.

//...Get dc's

BITMAP bm;
GetObject(hbmColour, sizeof(BITMAP), &bm);

SelectBitmap(hdcMem, hbmMask);
BitBlt(hdcWindow, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCAND);

SelectBitmap(hdcMem, hbmColour);
BitBlt(hdcWindow, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCPAINT);

//...clean up as necessary

The first one will black out the shape of the transparent image, and the second will fill in the colour.

3.3.4. How do I make an image transparent? (run-time)
Contributor: theForger
If you want to generate a mask on the fly you need to choose which colour you want as transparent, create the mask, and black out the transparent colour on the original. This function takes the colour image and a colourref of what colour you want transparent and creates the mask.

HBITMAP CreateBitmapMask(HBITMAP hbmColour, COLORREF crTransparent)
{
HDC hdcMem, hdcMem2;
HBITMAP hbmMask;
BITMAP bm;

/*
Create mask bitmap.
*/
GetObject(hbmColour, sizeof(BITMAP), &bm);
hbmMask = CreateBitmap(bm.bmWidth, bm.bmHeight, 1, 1, NULL);

hdcMem = CreateCompatibleDC(0);
hdcMem2 = CreateCompatibleDC(0);

SelectBitmap(hdcMem, hbmColour);
SelectBitmap(hdcMem2, hbmMask);

/*
Set the background colour of the colour image to the colour
you want to be transparent.
*/
SetBkColor(hdcMem, crTransparent);
/*
Copy the bits from the colour image to the B+W mask... everything
with the background colour ends up white while everythig else ends up
black...Just what we wanted.
*/
BitBlt(hdcMem2, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
/*
Take our new mask and use it to turn the transparent colour in our
original colour image to black so the transparency effect will
work right.
*/
BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem2, 0, 0, SRCINVERT);
/*
Clean up.
*/
DeleteDC(hdcMem);
DeleteDC(hdcMem2);

return hbmMask;
}

Now you can use the Mask and Colour images as in the previous example.

Technocrat
Feb 13th, 2001, 04:41 PM
Again for the 10th time or so thanks.
Worked like a charm.