WTL-Draw a bitmap with transparent color

class CWTLFrameView : public CWindowImpl<CWTLFrameView>
{
private:
    CBitmap m_BitmapSample;
    CBitmap m_BitmapMask;
public:
    DECLARE_WND_CLASS(NULL)
    BOOL PreTranslateMessage(MSG* pMsg)
    {
        pMsg;
        return FALSE;
    }
    BEGIN_MSG_MAP(CWTLFrameView)
        MSG_WM_CREATE(OnCreate)
        MSG_WM_PAINT(OnPaint)
    END_MSG_MAP()
    int OnCreate(LPCREATESTRUCT /*lpCreateStruct*/)
    {
        m_BitmapSample.LoadBitmap(IDB_BITMAP_SAMPLE);
        ATLASSERT(!m_BitmapSample.IsNull());
        
        CSize size;
        m_BitmapSample.GetSize(size);
        m_BitmapMask.CreateBitmap(size.cx,size.cy,1,1,NULL);
        CDC dcBmp, dcMask;
        dcBmp.CreateCompatibleDC(NULL);
        dcMask.CreateCompatibleDC(NULL);
        dcBmp.SaveDC();
        dcMask.SaveDC();
        dcBmp.SelectBitmap(m_BitmapSample);
        dcMask.SelectBitmap(m_BitmapMask);
        //Get the color of pixel on left and top corner 
        //as the tranparent color
        COLORREF clrTrans = dcBmp.GetPixel(1,1);
        dcBmp.SetBkColor(clrTrans);
        dcMask.BitBlt(0,0,size.cx,size.cy,dcBmp,0,0,SRCCOPY);
        dcBmp.SetBkColor(RGB(0,0,0));
        dcBmp.SetTextColor(RGB(255,255,255));
        dcBmp.BitBlt(0,0,size.cx,size.cy,dcMask,0,0,SRCAND);
        dcMask.RestoreDC(-1);
        dcBmp.RestoreDC(-1);
        return 0;
    }
    
    void OnPaint(CDCHandle /*dc*/)
    {
        CPaintDC dc(m_hWnd);
        //TODO: Add your drawing code here
        CDC dcBmp,dcMask;
        dcBmp.CreateCompatibleDC(dc);
        dcMask.CreateCompatibleDC(NULL);
        dcBmp.SaveDC();
        dcMask.SaveDC();
        dcBmp.SelectBitmap(m_BitmapSample);
        dcMask.SelectBitmap(m_BitmapMask);
        CSize size;
        m_BitmapSample.GetSize(size);
        dc.BitBlt(100,100,size.cx,size.cy,dcMask,0,0,SRCAND);
        dc.BitBlt(100,100,size.cx,size.cy,dcBmp,0,0,SRCPAINT);
        dcMask.RestoreDC(-1);
        dc.RestoreDC(-1);
    }
};

posted on 2010-09-28 15:04  wudong  阅读(1274)  评论(0编辑  收藏  举报

导航