Piszę klasę przycisku do sfml 2.5.1, która dziedziczy po sf::Drawable, aby móc być bezpośrednio renderowany przez okno. Klasa opisuje tekst na przycisku oraz tło przycisku. Niestety, gdy próbuję wyświetlić przycisk, wyświetla się tylko tekst bez tła. Sprawdziłem pozycje i skale, czcionki i tekstury są odpowiednio załadowane. metodę draw() pisałem zgodnie z przykładem w komentarzu w Drawable.hpp. Nie wiem dlaczego tak się dzieje. Klasa Button:
class Button : public sf::Drawable {
private:
sf::Sprite ButtonBackground;
sf::Text text;
sf::Vector2f centerText(const sf::Text& text, const sf::Sprite& button) const {
sf::FloatRect textRect = text.getLocalBounds();
return sf::Vector2f(button.getPosition().x + (button.getGlobalBounds().width - textRect.width) / 2.0f - textRect.left,
button.getPosition().y + (button.getGlobalBounds().height - textRect.height) / 2.0f - textRect.top);
}
void updateTextPosition() {
text.setPosition(centerText(text, ButtonBackground));
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const {
target.draw(ButtonBackground, states);
target.draw(text, states);
}
public:
//Constuctors
Button() {}
~Button() {};
Button(sf::Texture & texture, std::string string, sf::Vector2f position, sf::Font & font, int characterSize) {
ButtonBackground.setTexture(texture);
ButtonBackground.setPosition(position);
ButtonBackground.setScale(3, 3);
ButtonBackground.setOrigin(0, 0);
text.setString(string);
text.setFont(font);
text.setCharacterSize(characterSize);
updateTextPosition();
}
//Set
void setButtonTexture(sf::Texture& texture) {
ButtonBackground.setTexture(texture);
}
void setPosition(sf::Vector2f position) {
ButtonBackground.setPosition(position);
updateTextPosition();
}
void setFont(sf::Font& font) {
text.setFont(font);
updateTextPosition();
}
void setCharacterSize(int size) {
text.setCharacterSize(size);
updateTextPosition();
}
void setString(std::string string) {
text.setString(string);
updateTextPosition();
}
//Get
sf::Vector2f getPosition() {
return ButtonBackground.getPosition();
}
int getCharacterSize() {
return text.getCharacterSize();
}
std::string getString() {
return text.getString();
}
};
Obiekt jest inicjalizowany w ten sposób:
Button button(ButtonTex, "Przycisk", sf::Vector2f(0, 0), GlobalFont, 50);
A wyświetlany:
W.draw(button);
Obiekt jest wyświetlany jako ostatni.