我一直在尝试找到一个居中文本的公式,但我不能让它在所有长度的文本上工作,所以我有点卡住了,找不到一种方法来正确地将所有内容居中。这是我到目前为止所知道的:
void Button::set_pos(sf::Vector2f pos) {
button.setPosition(pos);
float pos_x = (pos.x + button.getLocalBounds().width/3.0f) -
(text.getGlobalBounds().width/2);
float pos_y = (pos.y + button.getLocalBounds().height/3.0f) -
(text.getGlobalBounds().height/2);
text.setPosition(pos_x, pos_y);
}但是,正如您所看到的,这并不适用于所有长度的文本

我怎样才能让它正确地居中呢?
发布于 2021-05-17 00:57:24
sfml中的文本从左下角开始,而不是左上角。我使用text.getLocalBounds()而不是text.getGlobalBounds()。这对我很有效。也有同样的问题。
另外,要确保文本不为空。ie在任何转换之前使用text.setString()。
发布于 2021-05-26 23:06:53
使用带有按钮的.getGlobalBounds()而不是.getLocalBounds()。这应该行得通。
void Button::set_pos(sf::Vector2f pos) {
button.setPosition(pos);
float pos_x = (pos.x + button.getGlobalBounds().width/3.0f) -
(text.getGlobalBounds().width/2);
float pos_y = (pos.y + button.getGlobalBounds().height/3.0f) -
(text.getGlobalBounds().height/2);
text.setPosition(pos_x, pos_y);
}https://stackoverflow.com/questions/67523148
复制相似问题