Advertisement
TermSpar

SFML Button Class

Apr 11th, 2019
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. // Made by Ben Bollinger
  2.  
  3. #pragma once
  4.  
  5. #include <iostream>
  6. #include <SFML/Graphics.hpp>
  7.  
  8. class Button {
  9. public:
  10.     Button(std::string btnText, sf::Vector2f buttonSize, int charSize, sf::Color bgColor, sf::Color textColor) {
  11.         button.setSize(buttonSize);
  12.         button.setFillColor(bgColor);
  13.  
  14.         // Get these for later use:
  15.         btnWidth = buttonSize.x;
  16.         btnHeight = buttonSize.y;
  17.  
  18.         text.setString(btnText);
  19.         text.setCharacterSize(charSize);
  20.         text.setColor(textColor);
  21.     }
  22.  
  23.     // Pass font by reference:
  24.     void setFont(sf::Font &fonts) {
  25.         text.setFont(fonts);
  26.     }
  27.  
  28.     void setBackColor(sf::Color color) {
  29.         button.setFillColor(color);
  30.     }
  31.  
  32.     void setTextColor(sf::Color color) {
  33.         text.setColor(color);
  34.     }
  35.  
  36.     void setPosition(sf::Vector2f point) {
  37.         button.setPosition(point);
  38.  
  39.         // Center text on button:
  40.         float xPos = (point.x + btnWidth / 2) - (text.getLocalBounds().width / 2);
  41.         float yPos = (point.y + btnHeight / 2.2) - (text.getLocalBounds().height / 2);
  42.         text.setPosition(xPos, yPos);
  43.     }
  44.  
  45.     void drawTo(sf::RenderWindow &window) {
  46.         window.draw(button);
  47.         window.draw(text);
  48.     }
  49.  
  50.     // Check if the mouse is within the bounds of the button:
  51.     bool isMouseOver(sf::RenderWindow &window) {
  52.         int mouseX = sf::Mouse::getPosition(window).x;
  53.         int mouseY = sf::Mouse::getPosition(window).y;
  54.  
  55.         int btnPosX = button.getPosition().x;
  56.         int btnPosY = button.getPosition().y;
  57.  
  58.         int btnxPosWidth = button.getPosition().x + btnWidth;
  59.         int btnyPosHeight = button.getPosition().y + btnHeight;
  60.  
  61.         if (mouseX < btnxPosWidth && mouseX > btnPosX && mouseY < btnyPosHeight && mouseY > btnPosY) {
  62.             return true;
  63.         }
  64.         return false;
  65.     }
  66. private:
  67.     sf::RectangleShape button;
  68.     sf::Text text;
  69.  
  70.     int btnWidth;
  71.     int btnHeight;
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement