Dan*_*ans 15 c++ linux 2d sfml
我正在使用Ubuntu 12.10上的SFML 2.0库
sudo apt-get install libsfml-dev
Run Code Online (Sandbox Code Playgroud)
得到他们.现在我试图让sf :: Text在sreen中居中.为此,我将文本的原点(用于进行转换的位置,如设置位置,旋转等)设置为sf :: Text的边界框的中心,然后将位置设置为屏幕中心,如下:
//declare text
sf::Font font;
sf::Text text;
font.loadFromFile("helvetica.ttf");
text.setFont(font);
text.setString("RANDOMTEXT");
text.setCharacterSize(100);
text.setColor(sf::Color::White);
text.setStyle(sf::Text::Regular);
//center text
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.width/2,textRect.height/2);
text.setPosition(sf::Vector2f(SCRWIDTH/2.0f,SCRHEIGHT/2.0f));
Run Code Online (Sandbox Code Playgroud)
这不起作用,文本偏离一些量,如x轴为3,y轴为25.奇怪的是,如果您设置一个sf :: RectangleShape来表示文本的边界框,那么该矩形将居中并且大小正确以适合文本.但是,然后使用前面提到的偏移量从该框中抽出文本.
在这张图片中,我标记了屏幕的中心,在文本边界框的位置绘制了sf :: RectangleShape,以及sf :: Text.
http://i.imgur.com/4jzMouj.png
该图像是由以下代码生成的:
const int SCRWIDTH = 800;
const int SCRHEIGHT = 600;
int main() {
sf::RenderWindow window;
window.create(sf::VideoMode(SCRWIDTH,SCRHEIGHT), "MYGAME" ,sf::Style::Default);
window.setMouseCursorVisible(false);
window.setVerticalSyncEnabled(true);
sf::Font font;
sf::Text text;
font.loadFromFile("helvetica.ttf");
text.setFont(font);
text.setString("RANDOMTEXT");
text.setCharacterSize(100);
text.setColor(sf::Color::White);
text.setStyle(sf::Text::Regular);
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.width/2,textRect.height/2);
text.setPosition(sf::Vector2f(SCRWIDTH/2.0f,SCRHEIGHT/2.0f));
sf::RectangleShape rect(sf::Vector2f(textRect.width,textRect.height));
rect.setFillColor(sf::Color::Blue);
rect.setOrigin(rect.getSize().x/2,rect.getSize().y/2);
rect.setPosition(text.getPosition());
sf::RectangleShape RectW;
RectW.setSize(sf::Vector2f(SCRWIDTH, 0.0));
RectW.setOutlineColor(sf::Color::Red);
RectW.setOutlineThickness(1);
RectW.setPosition(0, SCRHEIGHT / 2);
sf::RectangleShape RectH;
RectH.setSize(sf::Vector2f(0.0, SCRHEIGHT));
RectH.setOutlineColor(sf::Color::Red);
RectH.setOutlineThickness(1);
RectH.setPosition(SCRWIDTH / 2, 0);
while(window.isOpen()) {
window.clear();
window.draw(rect);
window.draw(text);
window.draw(RectW);
window.draw(RectH);
window.display();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
window.close();
}
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它居中并在它的边界框内,应该如此?
Emi*_*ier 28
sf::Text::getLocalBounds()对于top和left字段具有非零值,因此在将原点居中时不能忽略它们.
试试这个:
//center text
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.left + textRect.width/2.0f,
textRect.top + textRect.height/2.0f);
text.setPosition(sf::Vector2f(SCRWIDTH/2.0f,SCRHEIGHT/2.0f));
Run Code Online (Sandbox Code Playgroud)