1. Easy way to calculate text width!! no matter what font
- Posted by jordah at btopenworld.com Apr 01, 2003
- 728 views
i have just encountered some MFC C++ code that will save a few pple the hassle of finding text width. here is the routine; static int _CalcTextWidth(const CString& strText) { CWindowDC dc(NULL); CRect rcText(0, 0, 0, 0); CFont* pOldFont = dc.SelectObject(&_fontHorzMenu); dc.DrawText(strText, &rcText, DT_SINGLELINE | DT_CALCRECT); dc.SelectObject(pOldFont); return rcText.Width(); } What is basically happening is that the RECT structure is passed to the drawText() function with null values for all its elements. The drawText() function, on noticing this fills the structure with the text width. It calculates the width based on the font currently selected in the DC. I Hope this helps those out there who have once had to calculate text width the difficult way. Jordah
2. Re: Easy way to calculate text width!! no matter what font
- Posted by Elliott Sales de Andrade <quantum_analyst at hotmail.com> Apr 01, 2003
- 715 views
>From: jordah at btopenworld.com >Subject: Easy way to calculate text width!! no matter what font > > >i have just encountered some MFC C++ code that will save a few pple the >hassle of finding text width. here is the routine; > >static int _CalcTextWidth(const CString& strText) >{ > CWindowDC dc(NULL); > CRect rcText(0, 0, 0, 0); > CFont* pOldFont = dc.SelectObject(&_fontHorzMenu); > dc.DrawText(strText, &rcText, DT_SINGLELINE | DT_CALCRECT); > dc.SelectObject(pOldFont); > > return rcText.Width(); >} > >What is basically happening is that the RECT structure is passed to the >drawText() function with null values for all its elements. The drawText() >function, on noticing this fills the structure with the text width. It >calculates the width based on the font currently selected in the DC. Well, it's not doing this because the RECT is full of 0's, but because of the DT_CALCRECT flag. You can also find the height of the text as well. You may want to fill in the top and left parts of the structure if you want to get the bottom and right parts.... DrawText will not actually draw the text though, if DT_CALCRECT is specified. >I Hope this helps those out there who have once had to calculate text width >the difficult way. > >Jordah >