MFC——获取当前字体的高度、宽度等信息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanhuanxiaoxiao/article/details/84205583

当我们想往屏幕上面写多行内容时,我们需要之前当前文本的宽度和高度信息。我们可以采用以下方法:

void CDialogView::OnDraw(CDC* pDC)
{
	CDialogDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	if (!pDoc)
		return;

	CFont font;
	font.CreatePointFont(300,_T("华文行楷"));//创建一个大小为300,字体类型为华文行楷
	CFont* pOldFont;
	pOldFont = pDC->SelectObject(&font);//保存原先的字体
	CString strTemp(_T("你的职业是:"));
	switch(m_nOccupation)
	{
	case 0:
		strTemp += _T("程序员");
		break;
	case 1:
		strTemp += _T("系统工程师");
		break;
	case 2:
		strTemp += _T("项目经理");
		break;
	default:
		break;
	}
	pDC->TextOut(0,0,strTemp);//将内容打印
	strTemp = _T("你的工作点是:");
	strTemp += m_strWorkAddr;
	TEXTMETRIC tm;
	pDC->GetTextMetrics(&tm);//获取当前文本的信息,高度、宽度等
	pDC->TextOut(0,tm.tmHeight,strTemp);
	strTemp = _T("你的兴趣爱好是:");
	if(m_bFootBall)
	{
		strTemp += _T("足球 ");
	}
	if(m_bBasketBall)
	{
		strTemp += _T("篮球 ");
	}
	if(m_bVolleyball)
	{
		strTemp += _T("排球 ");
	}
	if(m_bPingPong)
	{
		strTemp += _T("乒乓球 ");
	}
	pDC->TextOut(0,tm.tmHeight * 2, strTemp);
	strTemp = _T("你的工资水平是:");
	strTemp += m_strSalary;
	pDC->TextOut(0,tm.tmHeight * 3, strTemp);
	pDC->SelectObject(pOldFont);
}
CDC::TextOut
virtual BOOL TextOut(
   int x,
   int y,
   LPCTSTR lpszString,
   int nCount 
);
BOOL TextOut(
   int x,
      int y,
      const CString& str 
);

Parameters
x
Specifies the logical x-coordinate of the starting point of the text.

y
Specifies the logical y-coordinate of the starting point of the text.

lpszString
Points to the character string to be drawn.

nCount
Specifies the number of bytes in the string.

str
A CString object that contains the characters to be drawn.
CDC::GetTextMetrics
BOOL GetTextMetrics(
   LPTEXTMETRIC lpMetrics 
) const;

Parameters
lpMetrics
Points to the TEXTMETRIC structure that receives the metrics

typedef struct tagTEXTMETRIC { 
  LONG tmHeight; 
  LONG tmAscent; 
  LONG tmDescent; 
  LONG tmInternalLeading; 
  LONG tmExternalLeading; 
  LONG tmAveCharWidth; 
  LONG tmMaxCharWidth; 
  LONG tmWeight; 
  LONG tmOverhang; 
  LONG tmDigitizedAspectX; 
  LONG tmDigitizedAspectY; 
  TCHAR tmFirstChar; 
  TCHAR tmLastChar; 
  TCHAR tmDefaultChar; 
  TCHAR tmBreakChar; 
  BYTE tmItalic; 
  BYTE tmUnderlined; 
  BYTE tmStruckOut; 
  BYTE tmPitchAndFamily; 
  BYTE tmCharSet; 
} TEXTMETRIC, *PTEXTMETRIC; 

GetTextExtent:获取特定的字符串在屏幕上所占的宽度和高度

    CTime t = CTime::GetCurrentTime();
	CString strTime = t.Format(_T("%H:%M:%S"));
	CClientDC dc(this);
	CSize sz = dc.GetTextExtent(strTime);//获取当前文本的宽度
	int index = m_wndStatusBar.CommandToIndex(IDS_TIMER);
	m_wndStatusBar.SetPaneInfo(index, IDS_TIMER, SBPS_NORMAL, sz.cx);//设置状态栏面板的宽度
	m_wndStatusBar.SetPaneText(index, strTime);

猜你喜欢

转载自blog.csdn.net/huanhuanxiaoxiao/article/details/84205583