场景:
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 );
注意: 这里有一点要注意的。就是destBmp在调用CreateCompatibleBitmap时,传递进去的第一个參数是CClientDC,不然生成的新的CBitmap会不是你想要的.
下边给出的是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; }
时间: 2024-10-24 14:06:30