gpt4 book ai didi

c++ - 显示来自另一个类的 sf::Text 对象的文本。 SFML

转载 作者:行者123 更新时间:2023-11-28 05:13:27 24 4
gpt4 key购买 nike

我正在尝试创建一个类,该类将创建一个带有一些白色文本的黑框。它最终将能够根据发送到类的字符串来缩放框的大小。但是,首先,我不知道为什么文本不显示。感谢您的帮助。

这是TextBox.h

class TextBox{

public:

sf::RectangleShape rect;
sf::Text text;
sf::Font font;

TextBox(std::string str, sf::Font f);
sf::Text getText();

这是在 TextBox.cpp 中找到的 TextBox 构造函数。我发送给构造函数的 sf::Font 是由 SFML 设置的字体。

#include "TextBox.h"
#include "string"

TextBox::TextBox(std::string str, sf::Font font){

rect.setFillColor(sf::Color::Black);
rect.setPosition(20, 20);
rect.setSize(sf::Vector2f(120,120));

text.setFont(font);
text.setString(str);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);

text.setPosition(rect.getPosition());

}

这是 main.cpp 中的代码,应该同时显示 Rect 和 Text

sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
return EXIT_FAILURE;
}

TextBox textBox("This Box", font);
textBox.text.setStyle(sf::Text::Bold);
// Start the game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window: exit
if (event.type == sf::Event::Closed) {
window.close();
}

// Escape pressed: exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}

// Clear screen
window.clear();

window.draw(textBox.rect);
window.draw(textBox.text);

// Update the window
window.display();

我尝试使用返回 sf::Text 对象的公共(public) getText() 方法,但它没有解决问题。此外,我对 rect 所做的修改起作用并显示了 rect。文本不是。

谢谢你,干杯

最佳答案

来自 sf::Text::setFont() method :

The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behavior is undefined.

.

在你的 TextBox 构造函数中,你将 font 作为 f 的拷贝传递,在初始化 textBox 之后,字体复制 f 将被销毁,因此您的 textBox.text 不会显示。

修复它很简单:通过使用传递(常量)引用按原样传递 font:TextBox(std::string str, const sf::Font& f);

(您可能还想将 std::string 作为 const 引用传递)

关于c++ - 显示来自另一个类的 sf::Text 对象的文本。 SFML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com