Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: bug whith Text class  (Read 1454 times)

0 Members and 1 Guest are viewing this topic.

Sanatostin

  • Newbie
  • *
  • Posts: 3
    • View Profile
    • Email
bug whith Text class
« on: April 09, 2018, 09:58:40 pm »
Hi!
First of all I want to say thanks for such a wonderful and simple graphicks libruary. I had a trouble whith Text class while coding. Hear two simplyfied code fragments:

this works properly:
#include <SFML/Graphics.hpp>
using namespace sf;

class A
{

public:
    void draw_on(RenderTarget & target)
    {
        Text text;
        Font font;
        font.loadFromFile("arial.ttf");
        text.setCharacterSize(100);
        text.setColor(Color::Red);
        text.setFont(font);
        text.setString("Experiment");
        target.draw(text);
    }
};


int main()
{
    sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window");
    A a;
    while (app.isOpen())
    {
        sf::Event event;
        while (app.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                app.close();
        }
        app.clear();
        a.draw_on(app);
        app.display();
    }
    return 0;
}
 

and shows red word "Experiment"

this one shows nothing:
#include <SFML/Graphics.hpp>
using namespace sf;

class A
{
    Text text;
public:
    void draw_on(RenderTarget & target)
    {
        Font font;
        font.loadFromFile("arial.ttf");
        text.setCharacterSize(100);
        text.setColor(Color::Red);
        text.setFont(font);
        text.setString("Experiment");
        target.draw(text);
    }
};


int main()
{
    sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window");
    A a;
    while (app.isOpen())
    {
        sf::Event event;
        while (app.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                app.close();
        }
        app.clear();
        a.draw_on(app);
        app.display();
    }
    return 0;
}
 

the difference is in place of declaration of Text text

Please, answer if you know why this happens.

Gleade

  • Jr. Member
  • **
  • Posts: 55
    • View Profile
Re: bug whith Text class
« Reply #1 on: April 10, 2018, 08:52:22 am »
In your first example, text is in the same scope as the font, both being re-created on every draw call. In your second example, text is now a class member; therefore, it's on a different scope level compared to the font.

I'm thinking that this must be the problem. As the font goes out of scope (therefore destroyed), the text would still have a reference to it. I believe the general rule is, to keep an object alive for as long as it is being referenced / pointed to. So in your case, you would want to make font a class member also - I'd also recommend loading the font before you render it (you're currently loading the font every draw call).

 

anything