C ++ sets transparent background images and background images
Background:
There are two images, one is the target background image and the other is a color image with its own background color.
First, draw the color image to the target background image, which can be achieved through BITBLT. However, the effect after implementation is: The color image on the target image has its own background.
The problem arises. How can we remove the background of the color image?
Solution:
API function: TransparentBlt this function draws images from the original DC to the Target DC, and sets the transparent color of the original image on the target image.
BOOL TransparentBlt( HDC hdcDest, // handle to destination DC int nXOriginDest, // x-coord of destination upper-left corner int nYOriginDest, // y-coord of destination upper-left corner int nWidthDest, // width of destination rectangle int hHeightDest, // height of destination rectangle HDC hdcSrc, // handle to source DC int nXOriginSrc, // x-coord of source upper-left corner int nYOriginSrc, // y-coord of source upper-left corner int nWidthSrc, // width of source rectangle int nHeightSrc, // height of source rectangle UINT crTransparent // color to make transparent );
In this example, when the transparent color is set to the color image with the background color, the background color of the final color image is eliminated after this function is used.
CDC * pDC = GetDC (); CBitmap bmp; bmp. loadBitmap (IDB_BITMAP1); BITMAP bmp Info; bmp. getObject (sizeof (BITMAP), & BMP info); CDC ImageDC; ImageDC. createCompatibleDC (pDC); CBitmap * pOldImageBmp = ImageDC. selectObject (& bmp); CBitmap bmp BK; bmp BK. loadBitmap (IDB_BITMAP2); bitmap bmp bkinfo; bmp bk. getObject (sizeof (BITMAP), & BMP bkinfo); CDC bkDC; bkDC. createCompatibleDC (pDC); bkDC. selectObject (& bmp bk); TransparentBlt (bkDC. m_hDC, 100,150, BMP info. bmWidth, BMP info. bmHeight, ImageDC. m_hDC, 0, 0, BMP info. bmWidth, BMP info. bmHeight, RGB (, 0); // set BitBlt (pDC-> m_hDC, BMP bkinfo in red. bmWidth, BMP bkinfo. bmHeight, bkDC. m_hDC, SRCCOPY); // draw to the screen
Principle: Implemented by setting a mask bitmap
1) first create a mask bitmap
2) apply a mask bitmap to the color source image to obtain a new variant image (the transparent color is black, and the other areas are primary colors)
3) use the mask bitmap and the target background image phase (transparent area is transparent, other areas are black)
4) use the new variant image to match the target background image or to obtain the final image.