Mam problem ze stworzeniem przycisku. Niby mam klasę z sf::Text i tłem sf::RectangleShape, ale nie wszystko układa się tak jakbym chciał. Trzeci przycisk jest przesunięty w kierunek dolnym-lewym o 1px. Z tego co udało mi się wydedukować to fakt, że dzieląc liczbę nieparzystą szerokości tekstu na pół w konstruktorze mogę tracić 1 piksel, ale to rozwiązywało mi tylko połowę problemu. Czy mógłbym moje przyciski lepiej wyśrodkować?
Plik main.cpp
#include <SFML\Graphics.hpp>
#include <vector>
#include "BasicButton.hpp"
int main()
{
sf::Font font;
if(!font.loadFromFile("ArchivoBlack-Regular.ttf")) return 1;
sf::RenderWindow window(sf::VideoMode(1024, 720), "Menu");
std::vector<BasicButton> buttons =
{
BasicButton(font, "Start", window.getSize().x / 2, window.getSize().y / 2 - 101, 200, 100),
BasicButton(font, "Opcje", window.getSize().x / 2, window.getSize().y / 2, 200, 100),
BasicButton(font, "Wyjscie", window.getSize().x / 2, window.getSize().y / 2 + 101, 200, 100)
};
for (auto& button : buttons)
button.setRectColor(sf::Color::Blue, sf::Color::Red);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed) window.close();
sf::Vector2f mousePos(sf::Mouse::getPosition(window));
for (auto& button : buttons)
button.setFocus(mousePos);
}
window.clear();
for (auto& button : buttons) button.draw(window);
window.display();
}
}
Plik BasicButton.hpp
#pragma once
#include <SFML/Graphics.hpp>
class BasicButton
{
sf::Text m_text;
sf::RectangleShape m_rect;
sf::Color m_normal_color;
sf::Color m_focus_color;
public:
BasicButton(const sf::Font&, const std::string&, float x, float y, float w, float h);
bool isFocus(const sf::Vector2f& v);
void setFocus(const sf::Vector2f& v);
void setRectColor(const sf::Color& normal, const sf::Color& focus);
void draw(sf::RenderWindow&);
};
Plik BasicButton.cpp
#include "BasicButton.hpp"
BasicButton::BasicButton(const sf::Font& font, const std::string& str, float x, float y, float w, float h)
{
m_text.setFont(font);
m_text.setString(str);
m_normal_color = sf::Color::Black;
m_focus_color = sf::Color::Black;
m_rect.setSize(sf::Vector2f(w, h));
m_text.setPosition(x, y);
auto global2 = m_text.getGlobalBounds();
m_text.setOrigin(global2.width / 2, global2.height / 2);
m_rect.setOrigin(w / 2, h / 2);
m_rect.setPosition(global2.left, global2.top);
}
void BasicButton::setRectColor(const sf::Color& normal, const sf::Color& focus)
{
m_rect.setFillColor(normal);
m_normal_color = normal;
m_focus_color = focus;
}
bool BasicButton::isFocus(const sf::Vector2f& vec)
{
return m_rect.getGlobalBounds().contains(sf::Vector2f(vec));
}
void BasicButton::setFocus(const sf::Vector2f& vec)
{
if (this->isFocus(vec))
{
m_rect.setFillColor(m_focus_color);
}
else if (m_rect.getFillColor() != m_normal_color)
{
m_rect.setFillColor(m_normal_color);
}
}
void BasicButton::draw(sf::RenderWindow& window)
{
window.draw(m_rect);
window.draw(m_text);
}