Link to home
Start Free TrialLog in
Avatar of gblxj
gblxj

asked on

Exact dimension of a text string?

I have some button control neek change it's caption often, so I need to adjust the button size when the text changed. I use CDC::GetTextExtent or CDC::GetOutputTextExtent to get the text dimension, but it seem's the size is not precision.

Any idea or answer is appreciated!
Avatar of Andrian
Andrian

You should use CFont or something related whit font instead of CDC .And don't forget that when you change the button's caption,you use "SetWindowText" or "SendMessage" from CWnd but not CDC(related with image)!
What can you do then?
//////////////////////////
1.Specify you Font ( set your own size!)
//////////////////////////
e.g:
CFontDialog dlg;
      dlg.DoModal();
      HFONT hFont ;
      hFont=::CreateFont(
            dlg.GetSize()/5,
            dlg.GetSize()/10,
            0,
            0,
            dlg.GetWeight(),
            (BYTE) dlg.IsItalic(),
            (BYTE) dlg.IsUnderline(),
            (BYTE) dlg.IsStrikeOut(),
            ANSI_CHARSET,
            OUT_DEVICE_PRECIS,
            CLIP_CHARACTER_PRECIS,
            PROOF_QUALITY,
            VARIABLE_PITCH,
            dlg.GetFaceName()//LPCTSTR lpszFacename
            );
      SetFont(m_Font.FromHandle(hFont),TRUE);
//////////////////////////
2.Then,you can approximately calculate the length of your text
(len ~ size*count).
e.g : 'i' and 'm' have not the same size!
like you say "it seem's the size is not precision".
//////////////////////////

Hi,

Try using
CDC::GetTextMetrics( LPTEXTMETRIC lpMetrics )

This structure will get u the information u want.

Hope this help u out

Cheers
Avatar of Zoppo
Hi gblxj,

There's an MSDN article ID: Q203099 with code how to calculate the exact extent of a string using CDC::BeginPath, CDC::EndPath and CDC::GetPath.

hope that helps,

ZOPPO
Avatar of gblxj

ASKER

Thanks all!

It's seem ZOPPO's comment is very interesting, I have never used BeginPath before, I'll try it shortly.
What about CDC::DrawText(...) using DT_CALCRECT
Hi,

Try something like this
/Get the DC
CClientDC dc(this);

//Have the string
CString str("xwiz");

//Width storage
int PaneWidth = 0;

//Get the length of string
int Len = str.GetLength();

//Calculate pane width from each char width
for(int Index = 0; Index < Len; Index++)
{
char ch = str[Index];
int Temp = 0;
dc.GetCharWidth(ch,ch,&Temp);
PaneWidth += Temp;
}

//PaneWidth will give the size

OR

Do this

TEXTMETRIC txtmat;    
CClientDC dc(this);
dc.GetTextMetrics(&txtmat);

CString str("df5656");
int Len = str.GetLength();
Len *= txtmat.tmMaxCharWidth;

Len will give the width.
Try it out.
VinExpert
ASKER CERTIFIED SOLUTION
Avatar of migel
migel

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gblxj

ASKER

>>Child controls uses parent window font

I think this is the point of all.

Thanx!