NasNas
An intuitive and beginner friendly 2D game framework for C++
NineSlice.hpp
1 // Created by Modar Nasser on 23/10/2021.
2 
3 #pragma once
4 
5 #include <SFML/Graphics/Drawable.hpp>
6 #include <SFML/Graphics/Texture.hpp>
7 #include <SFML/Graphics/Transformable.hpp>
8 #include <SFML/Graphics/RenderTexture.hpp>
9 #include <SFML/Graphics/VertexArray.hpp>
10 #include <SFML/System/Vector2.hpp>
11 
12 #include <NasNas/core/data/Rect.hpp>
13 
14 namespace ns::ui {
15  class NineSlice : public sf::Drawable, public sf::Transformable {
16  public:
17  enum class Mode { Stretch, Repeat };
18 
19  explicit NineSlice(Mode mode=Mode::Stretch);
20  explicit NineSlice(const sf::Texture& texture, Mode mode=Mode::Stretch);
21  NineSlice(const sf::Texture& texture, const sf::IntRect& rect, Mode mode=Mode::Stretch);
22 
23  void setMode(Mode mode);
24 
25  void setTexture(const sf::Texture& texture, bool reset_rect = false);
26  void setTextureRect(const sf::IntRect& rect);
27  void setSlices(int left, int right, int top, int bottom);
28 
29  void setSize(const sf::Vector2i& size);
30  void setSize(int width, int height);
31  auto getSize() -> const sf::Vector2f&;
32 
33  auto getGlobalBounds() const -> sf::FloatRect;
34 
35  private:
36  void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
37  void updateVertices();
38 
39  struct Slices {
40  enum { CENTER, LEFT, RIGHT, TOP, BOT, TL, TR, BL, BR };
41  ns::FloatRect center;
42  ns::FloatRect left;
43  ns::FloatRect top;
44  ns::FloatRect right;
45  ns::FloatRect bot;
46  ns::FloatRect topleft;
47  ns::FloatRect topright;
48  ns::FloatRect botleft;
49  ns::FloatRect botright;
50  };
51 
52  Mode m_mode;
53  sf::Vector2f m_size;
54  Slices m_texture_slices;
55  const sf::Texture* m_texture = nullptr;
56  ns::FloatRect m_texture_rect;
57  sf::VertexArray m_vertices;
58  };
59 }