Click here to Skip to main content
13,792,844 members
Click here to Skip to main content
Add your own
alternative version


79 bookmarked
Posted 24 Aug 2000
Licenced CPOL

Drawing Transparent Bitmap with ease with on the fly masks in MFC

, 24 Aug 2000
Rate this:
Please Sign up or sign in to vote.
A few routines that makes implementing the ideas in Chris Becke's GDI tutorial a snap


I finally managed to get transparent drawing working and made a few routines that makes it a snap. I adapted this code from an example Chris Becke's Bitmap Basics - A GDI tutorial.

The situation

I have a master picture with lots of images in it, the transparent areas are all in purple. At runtime I pick parts of this picture and BitBlt it on the screen while preserving the transparency.

Or maybe you have a bitmap that you wish to show transparently, just set the transparent areas to a unique color and use the routines below.

First the routines, at the end an example that puts it all together.

//** STEP 1: Load the bitmap into a CBitmap Object
BOOL CMyDlg::LoadFileBitmap(CBitmap* pBmp, LPCTSTR szFilename)
   return pBmp->Attach(LoadImage(NULL, szFilename, IMAGE_BITMAP, 0, 0,
                      LR_LOADFROMFILE | LR_DEFAULTSIZE));

//** STEP 2: Create the Mask and dump it into a CBitmap Object
void CMyDlg::PrepareMask( CBitmap* pBmpSource,
                          CBitmap* pBmpMask,
                          COLORREF clrpTransColor, // Pass null if unknown
                          int iTransPixelX,      // = 0
                          int iTransPixelY       // = 0
   BITMAP bm;

   // Get the dimensions of the source bitmap
   pBmpSource->GetObject(sizeof(BITMAP), &bm);

   // Create the mask bitmap
   pBmpMask->CreateBitmap( bm.bmWidth, bm.bmHeight, 1, 1, NULL);

   // We will need two DCs to work with. One to hold the Image
   // (the source), and one to hold the mask (destination).
   // When blitting onto a monochrome bitmap from a color, pixels
   // in the source color bitmap that are equal to the background
   // color are blitted as white. All the remaining pixels are
   // blitted as black.

   CDC hdcSrc, hdcDst;


   // Load the bitmaps into memory DC
   CBitmap* hbmSrcT = (CBitmap*) hdcSrc.SelectObject(pBmpSource);
   CBitmap* hbmDstT = (CBitmap*) hdcDst.SelectObject(pBmpMask);

   // Dynamically get the transparent color
   COLORREF clrTrans;
   if (clrpTransColor == NULL)
      // User did not specify trans color so get it from bmp
      clrTrans = hdcSrc.GetPixel(iTransPixelX, iTransPixelY);
      clrTrans = clrpTransColor;

   // Change the background to trans color
   COLORREF clrSaveBk  = hdcSrc.SetBkColor(clrTrans);

   // This call sets up the mask bitmap.
   hdcDst.BitBlt(0,0,bm.bmWidth, bm.bmHeight, &hdcSrc,0,0,SRCCOPY);

   // Now, we need to paint onto the original image, making
   // sure that the "transparent" area is set to black. What
   // we do is AND the monochrome image onto the color Image
   // first. When blitting from mono to color, the monochrome
   // pixel is first transformed as follows:
   // if  1 (black) it is mapped to the color set by SetTextColor().
   // if  0 (white) is is mapped to the color set by SetBkColor().
   // Only then is the raster operation performed.

   COLORREF clrSaveDstText = hdcSrc.SetTextColor(RGB(255,255,255));

   hdcSrc.BitBlt(0,0,bm.bmWidth, bm.bmHeight, &hdcDst,0,0,SRCAND);

   // Clean up by deselecting any objects, and delete the
   // DC's.



//** STEP 3: Drawing with Transparency. Call from OnPaint
void CMyDlg::DrawTransparentBitmap(CMemDC* pDC,
                                   int xStart,  int yStart,
                                   int wWidth,  int wHeight,
                                   CDC* pTmpDC,
                                   int xSource, // = 0
                                   int ySource  // = 0)

   // We are going to paint the two DDB's in sequence to the destination.
   // 1st the monochrome bitmap will be blitted using an AND operation to
   // cut a hole in the destination. The color image will then be ORed
   // with the destination, filling it into the hole, but leaving the
   // surrounding area untouched.

   CDC hdcMem;

   CBitmap* hbmT = hdcMem.SelectObject(&m_bmpMask);

   pDC->BitBlt( xStart, yStart, wWidth, wHeight, &hdcMem,
                xSource, ySource, SRCAND);

   // Also note the use of SRCPAINT rather than SRCCOPY.

   pDC->BitBlt(xStart, yStart, wWidth, wHeight, pTmpDC,
               xSource, ySource,SRCPAINT);

   // Now, clean up.

It is that simple. MSDN examples are very confusing. Chris Becke's examples are a lot better but in Win32. :)

So here is a example on how to put it together in a real life situation.

//** EXAMPLE: Drawing with Transparency

//** EXP STEP 1: Declarations & variables
In YourDlg.h, add the following

CBitmap m_bmpPlmain;
CBitmap m_bmpMask;

BOOL LoadFileBitmap(CBitmap* pBmp, LPCTSTR szFilename);

void PrepareMask( CBitmap* pBmpSource,
                  CBitmap* pBmpMask,
                  COLORREF clrpTransColor,
                  int iTransPixelX = 0,
                  int iTransPixelY = 0 );

void DrawTransparentBitmap (CMemDC* pDC,
                            int xStart, int yStart,
                            int wWidth, int wHeight,
                            CDC* pTmpDC,
                            int xSource = 0,
                            int ySource = 0);

//** EXP STEP 2: Load and Prepare the bitmaps

  // I'm loading from a bitmap file but this can come from resource as well
  if (!LoadFileBitmap(&m_bmpPLMain, "BmpWithHoles.bmp"))
    // Opps ... where did the picture go ??

  // Third param is NULL because I don't know the transparent color
  // but I know the trans color is at pixel 200, 50
  // or is you know the trans color(RED) then do the following
  //  PrepareMask( &m_bmpPLMain, &m_bmpMask, RGB(255, 0, 0));

  PrepareMask( &m_bmpPLMain, &m_bmpMask, NULL, 200, 50);


//** EXP STEP 3: Drawing the bitmaps

  CPaintDC dc(this);              // device context for painting
  CDC dcMem;                  // memory device context

  // Select the bmp into the tmp memory DC
  CBitmap* pOldBmp = (CBitmap*) dcMem.SelectObject(&m_bmpPLMain);

  DrawTransparentBitmap( &dc,           // The destination DC.
                         POP_X,         // Where to draw
                         POP_WIDTH,     // Width & Height
                         &dcMem,        // the DC holding the bmp
                         POP_BMP_X_OFF, // x & y pos in master bmp
  // Do whatever you want to do ...


//** EXP STEP 4: Cleaning Up ..
   // Dont forget to delete the bmp's

That's about it ...

Any mistakes, additions or optimizations, please feel free to point them out. Just send the comments to windev and/or


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Raja Segar
Malaysia Malaysia
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralNo Transparent Bitmap Pin
videoDev27-Aug-09 1:19
membervideoDev27-Aug-09 1:19 
GeneralExcellent solution! Pin
agua224-Apr-09 13:53
memberagua224-Apr-09 13:53 
GeneralResizing+transprency Pin
Ahmed Charfeddine2-Oct-07 0:23
memberAhmed Charfeddine2-Oct-07 0:23 
GeneralRe: Resizing+transprency Pin
Ahmed Charfeddine2-Oct-07 0:28
memberAhmed Charfeddine2-Oct-07 0:28 
QuestionBitBlt() to CBitmap or HBITMAP Pin
MacGadger7-Dec-06 22:34
memberMacGadger7-Dec-06 22:34 
Answer[Message Removed] Pin
immetoz1-Oct-08 10:40
memberimmetoz1-Oct-08 10:40 
GeneralCheck your posted code. Pin
shreejan19-Jan-06 16:30
membershreejan19-Jan-06 16:30 
QuestionIs this possible ? Pin
Anonymous3-Oct-05 3:57
memberAnonymous3-Oct-05 3:57 
GeneralHelp for eVC++ 4.0... Pin
jbdeuce2215-Nov-04 9:14
memberjbdeuce2215-Nov-04 9:14 
I am writing an application using embedded visual c++ 4.0 and I am having trouble with the offscreen buffering. I have searched the web over and over and they all lead me back to the simple techniques used in this article. However, I still see a bad screen flicker in my Pocket PC app no matter what technique I try.

My app is a Pocket PC 2003 MFC dialog based, where I am trying to draw to an offscreen bitmap and then use BitBlt() to load the bitmap. The flicker is actually worse when I use this technique over not doing any buffering.

Can anyone give me some advice or a pointer as to what needs to be done different for the pocket pc enviornment? Or better yet, possibly some sample code of a pocket pc app that is flicker free?
Generalthis is horrible complicated way Pin
naristov1-Sep-04 18:20
membernaristov1-Sep-04 18:20 
GeneralRe: this is horrible complicated way Pin
mvuong14-Sep-04 13:40
membermvuong14-Sep-04 13:40 
GeneralRe: this is horrible complicated way Pin
dinsh21-Jan-06 13:53
memberdinsh21-Jan-06 13:53 
GeneralRe: this is horrible complicated way Pin
Jason Tost17-Aug-06 12:41
memberJason Tost17-Aug-06 12:41 
GeneralRe: this is horrible complicated way Pin
MartinNohrRimage13-Mar-12 17:17
memberMartinNohrRimage13-Mar-12 17:17 
GeneralShould test code before release Pin
Lee Bamford5-May-04 5:34
memberLee Bamford5-May-04 5:34 
GeneralRe: Should test code before release Pin
Anonymous20-May-04 10:35
memberAnonymous20-May-04 10:35 
GeneralSolution to this problem Pin
Sergio del Valle2-Aug-04 8:19
memberSergio del Valle2-Aug-04 8:19 
Generalproblem Pin
David St. Hilaire1-Mar-04 11:23
memberDavid St. Hilaire1-Mar-04 11:23 
GeneralRe: problem Pin
MordachaiWolf22-May-07 6:15
memberMordachaiWolf22-May-07 6:15 
GeneralSyntax error in VC++ 7 Pin
namsaray10-Feb-04 12:16
membernamsaray10-Feb-04 12:16 
GeneralAnother Transparent Drawing Function using BitBlt Pin
tjcufpc26-Oct-03 18:04
membertjcufpc26-Oct-03 18:04 
GeneralRe: Another Transparent Drawing Function using BitBlt Pin
tjcufpc26-Oct-03 18:12
membertjcufpc26-Oct-03 18:12 
GeneralRe: Another Transparent Drawing Function using BitBlt Pin
Late6-Feb-06 2:27
memberLate6-Feb-06 2:27 
GeneralRe: Another Transparent Drawing Function using BitBlt Pin
jbandi8022-Sep-08 15:37
memberjbandi8022-Sep-08 15:37 
GeneralRe: Another Transparent Drawing Function using BitBlt Pin
amilkar24-Dec-11 20:01
memberamilkar24-Dec-11 20:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.181207.3 | Last Updated 25 Aug 2000
Article Copyright 2000 by Raja Segar
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid