我正在开发一个需要使用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中绘制过一次,否则不会发生这种情况。
我这样做是为了按钮的功能将字符串设置为另一个值,这具有正确设置原点和位置的效果。在容器的构造函数中设置字符串的值(在绘制之前)不会正确设置原点。
我花了一天时间在这上面,我不明白我错过了什么。任何帮助将不胜感激。
答案 0 :(得分:1)
在setString()函数之后调用setFont()函数,这意味着localBounds仍为0,因为没有字体来指示宽度或高度。