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

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);
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值