VC++中具有3D文本的按紐控件
可以用具有OwnerDraw風格實現上述目的。
1.運行AppWizard生成一個基于對話框的test工程,在對話框中加入一個CButton控件。在CButton控件的General屬性頁將控件的ID改為IDC_3DTEXTBTN,Caption改為“誰與爭瘋”,在控件Styles屬性頁選中OwnerDraw,其余設置保持默認。
2.用classwizard創建一個新類:C3dTextButton,基類為CButton。
3.為C3dTextButton類添加一個protected的函數void Draw(CDC* pDC, const CRect& rect, UINT state)。如下所示編寫代碼:
void C3dTextButton::Draw(CDC *pDC, const CRect &rect, UINT state) { CString text; GetWindowText(text); int l=text.GetLength(); CRect rectClient=rect; //獲得控件的字體 CFont* pFont=GetFont(); //確定所選字體有效高度和寬度 LOGFONT logfont; pFont->GetObject(sizeof(LOGFONT),&logfont); if(logfont.lfHeight==0)logfont.lfHeight=20; logfont.lfWidth=0;//寬度設為0,寬度值由高度確定 logfont.lfWeight=1000; logfont.lfEscapement=logfont.lfOrientation=0; CFont tryfont; VERIFY(tryfont.CreateFontIndirect(&logfont)); CFont* pFontOld=pDC->SelectObject(&tryfont); //根據控件大小,調整字體的高度,使文本與控件協調 CSize textSizeClient=pDC->GetTextExtent(text,l); if(rectClient.Width()*textSizeClient.cy>rectClient.Height()*textSizeClient.c x){ logfont.lfHeight=::MulDiv(logfont.lfHeight,rectClient.Height(),textSizeC lient.cy); } else{ logfont.lfHeight = ::MulDiv(logfont.lfHeight,rectClient.Width(),textSize Client.cx); } //創建并選擇協調后的字體 CFont font; font.CreateFontIndirect(&logfont); pDC->SelectObject(&font); textSizeClient=pDC->GetTextExtent(text,l); //確定文本與控件邊界的距離minx,miny int minx=rectClient.left+(rectClient.Width()-textSizeClient.cx)/2; int miny=rectClient.top+(rectClient.Height()-textSizeClient.cy)/2; int oldBkMode=pDC->SetBkMode(TRANSPARENT); COLORREF textcol=::GetSysColor(COLOR_BTNTEXT); COLORREF oldTextColor=pDC->SetTextColor(textcol); int cx = minx; int cy = miny; int s=(state&ODS_SELECTED)?-1:+1; cx+= 3; cy+= 3; //實現3D效果 pDC->SetTextColor(::GetSysColor(COLOR_3DDKSHADOW)); pDC->TextOut(cx-s*2,cy+s*2,text); pDC->TextOut(cx+s*2,cy-s*2,text); pDC->TextOut(cx+s*2,cy+s*2,text); pDC->SetTextColor(::GetSysColor(COLOR_3DHILIGHT)); pDC->TextOut(cx+s*1,cy-s*2,text); pDC->TextOut(cx-s*2,cy+s*1,text); pDC->TextOut(cx-s*2,cy-s*2,text); pDC->SetTextColor(::GetSysColor(COLOR_3DSHADOW)); pDC->TextOut(cx-s*1,cy+s*1,text); pDC->TextOut(cx+s*1,cy-s*1,text); pDC->TextOut(cx+s*1,cy+s*1,text); pDC->SetTextColor(::GetSysColor(COLOR_3DLIGHT)); pDC->TextOut(cx,cy-s*1,text); pDC->TextOut(cx-s*1,cy,text); pDC->TextOut(cx-s*1,cy-s*1,text); pDC->SetTextColor(textcol); //輸出標題 pDC->TextOut(cx,cy,text); //恢復設備描述表 pDC->SetTextColor(oldTextColor); pDC->SetBkMode(oldBkMode); pDC->SelectObject(pFontOld); }
4.用classwizard重載C3dTextButton類的DrawItem函數。編寫代碼如下所示:
void C3dTextButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pDC=CDC::FromHandle(lpDrawItemStruct->hDC); ASSERT_VALID(pDC); CRect rectClient=lpDrawItemStruct->rcItem; Draw(pDC,rectClient,lpDrawItemStruct->itemState); }
5.用classwizard為IDC_3DTEXTBTN建立一個C3dTextButton控件變量m_3dTextButton1。
6.把“3dTextButton.h”加入testDlg頭文件。
7.編譯并測試應用程序。好了,可以欣賞一下勞動成果了。