如何缩放CBitmap对象?

时间:2010-05-05 05:37:34

标签: c++ mfc gdi+ resize cbitmap

我从资源ID加载了一个CBitmap对象,我现在想要在每个维度中将其缩放到50%。我怎么能这样做?

3 个答案:

答案 0 :(得分:5)

  1. 选择您的CBitmap obj到memDC A(使用CDC :: SelectObject())
  2. 创建一个具有所需大小的新CBitmap并将其选择到另一个MemDC B
  3. 使用CDC :: stretchblt(...)将MemDC A中的bmp拉伸到MemDC B中
  4. 取消选择您的CBitmap对象(通过选择之前对SelectObject的调用返回的内容)
  5. 使用新的CBitmap

答案 1 :(得分:1)

这是@ Smashery的答案的实施。

我使用它来根据DPI进行缩放,但它应该很容易适应任意比例。

std::shared_ptr<CBitmap> AppHiDpiScaleBitmap (CBitmap &bmp)
{
    BITMAP bm = { 0 };
    bmp.GetBitmap (&bm);
    auto size = CSize (bm.bmWidth, bm.bmHeight);

    CWindowDC screenCDC (NULL);
    auto dpiX = screenCDC.GetDeviceCaps (LOGPIXELSX);
    auto dpiY = screenCDC.GetDeviceCaps (LOGPIXELSY);

    auto hiSize = CSize ((dpiX * size.cx) / 96, (dpiY * size.cy) / 96);

    std::shared_ptr<CBitmap> res (new CBitmap ());
    res->CreateCompatibleBitmap (&screenCDC, hiSize.cx, hiSize.cy);

    CDC srcCompatCDC;
    srcCompatCDC.CreateCompatibleDC (&screenCDC);
    CDC destCompatCDC;
    destCompatCDC.CreateCompatibleDC (&screenCDC);

    CMemDC srcDC (srcCompatCDC, CRect (CPoint (), size));
    auto oldSrcBmp = srcDC.GetDC ().SelectObject (&bmp);

    CMemDC destDC (destCompatCDC, CRect(CPoint(), hiSize));
    auto oldDestBmp = destDC.GetDC ().SelectObject (res.get());

    destDC.GetDC ().StretchBlt (0, 0, hiSize.cx, hiSize.cy, &srcDC.GetDC(), 0, 0, size.cx, size.cy, SRCCOPY);

    srcDC.GetDC ().SelectObject (oldSrcBmp);
    destDC.GetDC ().SelectObject (oldDestBmp);

    return res;
}

答案 2 :(得分:0)

void ResizeBitmap (CBitmap &bmp_src, CBitmap& bmp_dst, int dstW, int dstH)
{
BITMAP bm = { 0 };
bmp_src.GetBitmap (&bm);
auto size = CSize (bm.bmWidth, bm.bmHeight);
CWindowDC wndDC(NULL);
CDC srcDC;
srcDC.CreateCompatibleDC(&wndDC);
auto oldSrcBmp = srcDC.SelectObject(&bmp_src);

CDC destDC;
destDC.CreateCompatibleDC(&wndDC);
bmp_dst.CreateCompatibleBitmap (&wndDC, dstW, dstH);
auto oldDestBmp = destDC.SelectObject (&bmp_dst);

destDC.StretchBlt(0, 0, dstW, dstH, &srcDC, 0, 0, size.cx, size.cy, SRCCOPY);
}