【发布时间】:2018-07-03 17:08:47
【问题描述】:
我正在处理一个需要使用 SFML 完成一些按钮的项目。我们使用的是 2.4.2 版本。除了文本对齐之外,我已经设法完成了所有工作,但我对问题所在感到非常困惑。
为了设置文本的对齐方式,我知道我必须正确设置它的原点和位置。由于人们可能会更改按钮的文本,因此我决定将对齐功能放入 setString 函数中。
出于调试目的,我添加了几个控制台输出来显示我的一些数据。函数如下所示:
void rgf::Button::setString(const sf::String & str)
{
text.setString(str);
std::cout << "Original Origin: " << text.getOrigin().x << ", " << text.getOrigin().y << std::endl;
std::cout << "Original Position: " << text.getPosition().x << ", " << text.getPosition().y << std::endl;
std::cout << "Original LocalBounds: " << text.getLocalBounds().width << ", " << text.getLocalBounds().height << std::endl;
auto textRect = text.getLocalBounds();
auto btnRect = body.getLocalBounds();
text.setOrigin(textRect.left + textRect.width / 2, textRect.height + textRect.height / 2);
text.setPosition(btnRect.left + btnRect.width / 2, btnRect.top + btnRect.height / 2);
std::cout << "New Origin: " << text.getOrigin().x << ", " << text.getOrigin().y << std::endl;
std::cout << "New Position: " << text.getPosition().x << ", " << text.getPosition().y << std::endl;
std::cout << "New LocalBounds: " << text.getLocalBounds().width << ", " << text.getLocalBounds().height << std::endl;
}
控制台将所有新旧位置输出为 0(返回预期坐标 50 和 25 的新位置除外)。
根据我在网上找到的,一旦我设置了文本的字符串,我的文本对象的 localBounds 应该会改变。除非文本已经在 sf::RenderWindow 中绘制过一次,否则不会发生这种情况。
我这样做是为了让按钮的功能将字符串设置为另一个值,这具有正确设置原点和位置的效果。在容器的构造函数中设置字符串的值(在绘制之前)不会正确设置原点。
我在这上面花了一天时间,但我不明白我错过了什么。任何帮助将不胜感激。
【问题讨论】:
-
sf::Text::getLocalBounds()和sf::Text::draw()都调用同一个内部成员来更新几何,所以应该没有任何区别。您是否在更新文本之前分配了sf::Font?
标签: c++ text sfml text-alignment