创建透明按钮的简单方法






4.74/5 (13投票s)
2003年11月20日
1分钟阅读

144662

8413
关于所有者绘制按钮的文章
引言
我想要绘制一个对背景图像透明的按钮,为此我查阅了许多关于按钮样式 - 透明按钮的文章。它们都非常繁琐,需要擦除按钮背景、绘制图片等等。我发现了一种简单的方法。其思想是在对话框上绘制一张位图。将相同的位图从按钮的LeftTop
位置绘制到按钮上。除非鼠标光标移动到按钮上,否则按钮看起来不像一个按钮。因此,我将在按钮上添加两个图标。
//I have implemented two important functions -
//SetTransparent() and PaintBG(CDC *pDC, CRect rc)
//SetTranparent function loads bitmap from the resource and
//creates an handle to CDC - m_hHdc.
void CBut::SetTransparent()
{
HBITMAP m_hBmp = ::LoadBitmap(::AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDB_BITMAP6));
m_hHdc = ::CreateCompatibleDC(NULL);
::SelectObject(m_hHdc, m_hBmp);
}
//PaintBG function is called in DrawItem function which draws
//bitmap on the button from the location left-top of the button.
void CBut::PaintBG(CDC *pDC, CRect rc)
{
CRect rect;
GetWindowRect(rect);
GetParent()->ScreenToClient(rect);
if(m_hHdc!=NULL)
::BitBlt(pDC->m_hDC, rc.left, rc.top, rect.Width(),
rect.Height(), m_hHdc, rect.left, rect.top, SRCCOPY);
}
如何使用源代码文件
在你的CDialog
派生类的CPaint
函数中绘制位图到对话框上。 检查按钮的'OwnerDraw'
属性。 在dialog
类中创建一个CButtonStyle
类型的变量。 不要忘记在同一个类中包含ButtonStyle.h 文件名。
void CButtonStyleDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
....................
............
}
else
{
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);
//ScreenToClient(rect);
BITMAP bmp;
HBITMAP hBmp = ::LoadBitmap(::AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDB_BITMAP1));
::GetObject(hBmp, sizeof(bmp), &bmp);
HDC hDC = ::CreateCompatibleDC(NULL);
SelectObject(hDC, hBmp);
//Note: Do not use StretchBlt function.
::BitBlt(dc.m_hDC, 0, 0, rect.Width(), rect.Height(), hDC, 0, 0,
SRCCOPY);
CDialog::OnPaint();
}
}
//Set button properties in OnInitDialog() function of CDialog derived class
BOOL CButtonStyleDlg::OnInitDialog()
{
CDialog::OnInitDialog();
.......................
.........
..................
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_btnButton1.SetTransparent();
m_btnButton1.SetTextColor(RGB(0,220,0), RGB(0,255,0));
m_btnButton1.SetIcons(IDI_ICON4, IDI_ICON4);
m_btnButton1.FontStyle("MS Sans Serif");
m_btnOK.SetTransparent();
m_btnOK.SetTextColor(RGB(0,220, 0), RGB(0,255,0));
m_btnOK.SetIcons(IDI_ICON2, IDI_ICON2);
m_btnOK.FontStyle("MS Sans Serif");
m_btnExit.SetTransparent();
m_btnExit.SetTextColor(RGB(0,220,0), RGB(0,255,0));
m_btnExit.SetIcons(IDI_ICON1, IDI_ICON1);
m_btnExit.FontStyle("MS Sans Serif");
m_btnClick.SetTransparent();
m_btnClick.SetTextColor(RGB(0,220,0), RGB(0,255,0));
m_btnClick.SetIcons(IDI_ICON3, IDI_ICON5);
m_btnClick.FontStyle("MS Sans Serif");
return TRUE; // return TRUE unless you set the focus to a control
}
许可证
本文没有附加明确的许可协议,但可能包含在文章正文或下载文件中本身的使用条款。 如有疑问,请通过下面的讨论区联系作者。 可以在此处找到作者可能使用的许可协议列表。