VC 如何在一个矩形框中居中显示一个长字符串

2023-05-16

VC 如何在一个矩形框中居中显示一个长字符串
先使用 DT_WORDBREAK 和 DT_CALCRECT标志位调用 DrawText函数获得文字的外框尺寸
再使用将该外框尺寸居中显示实际绘制到窗口矩形框中。示例代码和界面效果图如下所示:
void CPlainCellNode::Draw(CDC* pDC)
{
	if (m_nCols <= 0 || m_nRows <= 0)
		return;

	if (m_bHide)
		return;

	CRect rc = GetDevRect();
	if (rc.Width() <= 0 || rc.Height() <= 0)
		return;

	CRect rcWnd;
	m_pHost->GetClientRect(rcWnd);

	if (rc.left >= rcWnd.right)
		return;

	if (rc.top >= rcWnd.bottom)
		return;

	if (rc.right <= rcWnd.left + CCellSheetWnd::s_nLeftBarWidth)
		return;

	if (rc.bottom <= rcWnd.top + CCellSheetWnd::s_nHeadeHeight)
		return;

	CRgn rgn;
	rgn.CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
	pDC->SelectClipRgn(&rgn);

	CRect rcBk = rc;
	rcBk.top += 1;
	rcBk.left += 1;
	pDC->FillRect(rcBk, &m_brBak);
	
	pDC->SelectObject(&GetCellGuiPool()->m_CellFont[m_nFontIndex]);
	UINT nAln = DT_LEFT;
	if (m_nCellAlign == cat_middle)
		nAln = DT_CENTER;

	CRect rcx = rc;
	pDC->SetBkMode(TRANSPARENT);
	pDC->SetTextColor(m_clrTxt);
	pDC->SetBkColor(m_clrBack);

	int h = pDC->DrawText(m_strText, rcx, DT_TOP | DT_LEFT | DT_WORDBREAK | DT_CALCRECT | DT_EDITCONTROL); // 获得文本高度 
	int dh = (rc.Height() - h) / 2;
	int dw = (rc.Width() - rcx.Width()) / 2;
	rcx.top = rc.top + dh;
	rcx.bottom = rc.bottom - dh;

	if (nAln == DT_CENTER)
	{
		rcx.left += dw;
		rcx.right += dw;
	}

	pDC->DrawText(m_strText, rcx , DT_TOP | nAln | DT_WORDBREAK); 
	pDC->SelectClipRgn(NULL);
}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VC 如何在一个矩形框中居中显示一个长字符串 的相关文章

随机推荐