场景:
1.当你需要截取图片部分区域作为某个控件的背景。
2.需要平铺图片到一个大区域让他自动放大时。
3.或者需要合并图片时。
代码:
CDC sdc; CDC ddc; sdc.CreateCompatibleDC(NULL); ddc.CreateCompatibleDC(NULL); CBitmap destBmp; destBmp.CreateCompatibleBitmap(CClientDC(NULL),width,height); sdc.SelectBitmap(m_Bitmap); ddc.SelectBitmap(destBmp); ddc.BitBlt(0, 0, width, height, sdc, rect.left, rect.top, SRCCOPY );
下边给出的是MFC api复制HBITMAP 对象,部分代码来自网上.
复制HBITMAP对象.
static HBITMAP CopyBitmap(HBITMAP hSourceHbitmap,long width,long height,int srcx,int srcy) { CDC sourceDC; CDC destDC; sourceDC.CreateCompatibleDC(NULL); destDC.CreateCompatibleDC(NULL); //The bitmap information. BITMAP bm = {0}; //Get the bitmap information. ::GetObject(hSourceHbitmap, sizeof(bm), &bm); // Create a bitmap to hold the result HBITMAP hbmResult = ::CreateCompatibleBitmap(CClientDC(NULL), width, height); HBITMAP hbmOldSource = (HBITMAP)::SelectObject( sourceDC.m_hDC, hSourceHbitmap); HBITMAP hbmOldDest = (HBITMAP)::SelectObject( destDC.m_hDC, hbmResult ); destDC.BitBlt(0,0,width, height, sourceDC, srcx, srcy, SRCCOPY ); // Restore DCs ::SelectObject( sourceDC.m_hDC, hbmOldSource ); ::SelectObject( destDC.m_hDC, hbmOldDest ); ::DeleteObject(sourceDC.m_hDC); ::DeleteObject(destDC.m_hDC); return hbmResult; }