矩形文本居中无效

Centering text on a rectangle not working

本文关键字:无效 文本      更新时间:2023-10-16

我有一个sf::RectangleShape inputFieldRect_sf::Text inputFieldText_,我想把文本放在矩形的中心,因为sf:: text的尺寸会变化,因为它的字符串会有不同的长度。

inputFieldText_.setString(s);设置inputFieldText_的字符串后(s是用户输入的std::string),我正在调整它的位置,使它仍然在inputFieldRect_的中心。

这是我的代码但是文本偏左偏下,所以没有完全居中

sf::FloatRect rectBounds = inputFieldRect_.getGlobalBounds();
sf::FloatRect textBounds = inputFieldText_.getGlobalBounds();
inputFieldText_.setPosition(
  rectBounds.left + (rectBounds.width / 2) - (textBounds.width / 2), 
  rectBounds.top + (rectBounds.height / 2) - (textBounds.height / 2)
);

有人能帮帮我吗?

如果文本的数量非常小,我建议您查看文本的绘制点在哪里:通常从文本基线(Y)和从第一个字符的逻辑初始X绘制文本。合乎逻辑,因为这可能比你预期的更正确。**

如果这没有帮助,调查是否应该使用LocalBounds可能是有用的:有时在框架中,差异并不像看起来那么简单。

**这个区别被称为左轴承(是的,也有右轴承)。详见本页备注:http://msdn.microsoft.com/en-us/library/system.windows.media.glyphrundrawing(v=vs.110).aspx