class DemoDuilib : public WindowImplBase, public CButtonUI { public: DemoDuilib(); ~DemoDuilib(); void test(); static std::vector<uint8_t> thumbData;//存储BLOB类型二进制数据 private: void PaintStatusImage(HDC hDC) override;//保持纵横比并裁剪 HBITMAP CreateHBITMAPFromMemory(const std::vector<uint8_t>& data);//BLOB类型二进制数据转换成Bitmap类型数据 ) void test(){ DemoDuilib* pButton = new DemoDuilib(); CDuiString strName; strName.Format(_T("btn_square_%d"), i + 1); pButton->SetName(strName); pButton->SetFixedHeight(BUTTONSIZE);//const int BUTTONSIZE = 85; pButton->SetFixedWidth(BUTTONSIZE); HBITMAP hBitmap = CreateHBITMAPFromMemory(thumbData); if (hBitmap) { pButton->SetNormalImage(hBitmap); } pButton->SetPadding(CDuiRect(10,0,0,0)); pButtonLayout->Add(pButton); }
void DemoDuilib::PaintStatusImage(HDC hDC) { if (m_hNormalBitmap) { HDC hMemDC = CreateCompatibleDC(hDC); HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, m_hNormalBitmap); BITMAP bitmap; GetObject(m_hNormalBitmap, sizeof(bitmap), &bitmap); float aspectRatio = static_cast<float>(bitmap.bmWidth) / bitmap.bmHeight; int targetWidth = m_rcItem.right - m_rcItem.left; int targetHeight = m_rcItem.bottom - m_rcItem.top; int newWidth, newHeight; if (aspectRatio > 1.0f) { newWidth = targetWidth; newHeight = static_cast<int>(targetWidth / aspectRatio); } else { newHeight = targetHeight; newWidth = static_cast<int>(targetHeight * aspectRatio); } int offsetX = (targetWidth - newWidth) / 2; int offsetY = (targetHeight - newHeight) / 2; StretchBlt(hDC, m_rcItem.left, m_rcItem.top, targetWidth, targetHeight, hMemDC, 0, 0, bitmap.bmWidth, bitmap.bmHeight, SRCCOPY); SelectObject(hMemDC, hOldBitmap); DeleteDC(hMemDC); } else { CButtonUI::PaintStatusImage(hDC); } } HBITMAP DemoDuilib::CreateHBITMAPFromMemory(const std::vector<uint8_t>& data) { HBITMAP hBitmap = NULL; Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); IStream* pStream = SHCreateMemStream(data.data(), data.size()); if (pStream) { Gdiplus::Bitmap* pBitmap = Gdiplus::Bitmap::FromStream(pStream); if (pBitmap) { pBitmap->GetHBITMAP(Gdiplus::Color(0, 0, 0), &hBitmap); delete pBitmap; } pStream->Release(); } Gdiplus::GdiplusShutdown(gdiplusToken); return hBitmap; }
标签:DemoDuilib,pButton,HBITMAP,缩略图,bitmap,Gdiplus,BLOB,hBitmap,Bitmap From: https://www.cnblogs.com/mengyaoli/p/18309251