c++ - MFC中如何让背景变成半透明?

标签 c++ mfc

我在 MFC 中导入图片(.bmp 或 .jpeg)作为客户端 View 的背景。

当我点击打开时,函数CDrawToolView::OnFileOpen()打开一个窗口来选择图片,然后我使用ShowBitmap(CDC* pDC,CString strPicPath)ShowPic(CDC* pDC,CString strPicPath) 将图片加载为背景并调整客户端 View 的大小以适合图片。

我想把图片设置成半透明的,让背景看起来更柔和。有人可以帮助我或提出一些建议吗,谢谢。

这是我的代码:

void CDrawToolView::ShowBitmap(CDC* pDC,CString strPicPath)
{        
    HBITMAP hBitmap=(HBITMAP)LoadImage(NULL,strPicPath,IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_LOADFROMFILE);
    m_bitmap.Detach();
    m_bitmap.Attach(hBitmap);

    CRect rect;
    GetClientRect(&rect);

    CDC dcImage;
    if (!dcImage.CreateCompatibleDC(pDC))
    {
        return;
    }

    BITMAP bm;
    m_bitmap.GetBitmap(&bm);
    dcImage.SelectObject(&m_bitmap);
    pDC->StretchBlt(0,0,rect.right,rect.bottom,&dcImage,0,0,bm.bmWidth,bm.bmHeight,SRCCOPY); 
}


void CDrawToolView::ShowPic(CDC* pDC,CString strPicPath)
{        
    if(!m_MyImage.IsNull())
        m_MyImage.Destroy();
    HRESULT hResult=m_MyImage.Load(strPicPath);
    int iWidth=m_MyImage.GetWidth();
    int iHeight=m_MyImage.GetHeight();
    m_MyImage.Draw(pDC->m_hDC,0,0,iWidth,iHeight);
    CRect client(0, 0, iWidth, iHeight);
    client.bottom=client.bottom+::GetSystemMetrics(SM_CYMENU)+::GetSystemMetrics(SM_CYEDGE)*2;
    client.right=client.right+::GetSystemMetrics(SM_CXEDGE)*2;
    CFrameWnd* pFrame = GetParentFrame(); 
    pFrame->CalcWindowRect(&client);
    int width  = client.Width();
    int height = client.Height();
    int y  = (::GetSystemMetrics(SM_CYSCREEN) - height) / 2 + 100;
    int x  = (::GetSystemMetrics(SM_CXSCREEN) - width) / 2;
    pFrame->SetWindowPos( NULL, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER );
}

最佳答案

使用 AlphaBlend 代替 StretchBlt

CDC::AlphaBlend

BLENDFUNCTION 结构中的 SourceConstantAlpha 设置为 128 之类的值(介于透明和不透明之间),然后进行调整,直到它看起来不错。

除非您使用带有 alpha channel 的 32 位位图,否则 AlphaFormat 应该为零。

关于c++ - MFC中如何让背景变成半透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19269866/

相关文章:

c++ - 如何从文件c++中读取每一行

c++ - 带状态的 C+11 策略模式

c++ - CTimeSpan.GetDays() 和夏令时

c++ - dll 中的资源字符串在程序中加载后不完全可见

c++ - 计算文本文件中的行数

c++ - 如何将 wchar_t 转换为 int 以显示代码点?

c++ - 值类型在map中的地址

winapi - 如何防止 MFC 中基于 CScrollView/CFormView 的类中的滚动条 (Windows Mobile 6)

C++ Windows API - 如何使用 ListView 的默认 WIndows Proc?

c++ - 具有相对路径的 CFileDialog