How to find width and height of the specified string of text

11 02 2012

Whenever we draw formatted text on a window, sometimes it would be really useful if you know the exact dimensions (width and height) required to draw it before actual drawing.

The DrawText function draws formatted text in the specified rectangle. But if we need to find the width and height to draw that text use this function with DT_CALCRECT flag as the last parameter of this function.
Also you can use another function GetTextExtentPoint32 to computes the width and height of the specified string.

Uisng DrawText

void ComputeWidthAndHeight(CDC* pDC)
{
	RECT rt = { 0, 0, 0, 0 };
	CString str = "ComputeWidthAndHeightToWriteText";
	DrawText(pDC->m_hDC, str, str.GetLength(), &rt, DT_CALCRECT);
}

Using GetTextExtentPoint32

void ComputeWidthAndHeight(CDC* pDC)
{
	CString str = "ComputeWidthAndHeightToWriteText";
	SIZE sz;
	GetTextExtentPoint32( pDC->m_hDC, str, str.GetLength(), &sz);
}

Please you don’t forget that using DT_CALCRECT will not draw the text, so a subsequent call to DrawText is required.

Advertisements

Actions

Information

One response

14 01 2014
Joaquim

i love your code and explication.
i have 1 question: if the DrawText() is for formated text, why ignores the tab size?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: