我正在使用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)); …Run Code Online (Sandbox Code Playgroud)