点和文本都给出了 100, 100 的位置,但 y 中的文本位于点下方
距离因字体而异
默认比例和原点
getLocalBounds表示正确的大小
`int main() { sf::RenderWindow 窗口(sf::VideoMode(800U, 600U), "标题",sf::Style::Close);
sf::RectangleShape bot(sf::Vector2f(1.0f, 1.0f));
sf::Text text;
sf::Font font;
font.loadFromFile("Data/Textures/Font/Retron2000.ttf");
bot.setFillColor(sf::Color::Black);
bot.setPosition(100.0f, 100.0f);
text.setFont(font);
text.setString("Hello");
text.setPosition(100.0f, 100.0f);
text.setFillColor(sf::Color::Black);
while (window.isOpen())
{
window.clear(sf::Color::White);
window.draw(bot);
window.draw(text);
window.display();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
}
}`
所以实际上,文本的位置通常与基线对齐,而不是与字符边界框的左上角对齐。
这是一个用人工智能清理和记录的可能解决方案:
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(800U, 600U), "Title", sf::Style::Close);
// Create a 1x1 rectangle (essentially a point)
sf::RectangleShape bot(sf::Vector2f(1.0f, 1.0f));
bot.setFillColor(sf::Color::Black);
bot.setPosition(100.0f, 100.0f); // Set position of the point
// Load font and create text
sf::Text text;
sf::Font font;
if (!font.loadFromFile("Data/Textures/Font/Retron2000.ttf")) {
return -1; // If font loading fails, exit the program
}
text.setFont(font);
text.setString("Hello");
text.setFillColor(sf::Color::Black);
// Adjust the text position to match the top-left of the bounding box
sf::FloatRect textBounds = text.getLocalBounds();
text.setPosition(100.0f, 100.0f - textBounds.top);
// Main loop
while (window.isOpen()) {
window.clear(sf::Color::White);
// Draw point and text
window.draw(bot);
window.draw(text);
window.display();
// Handle events
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
}
return 0;
}
希望这有效。