|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <SFML/Graphics.hpp> int main() { // Create a window sf::RenderWindow window(sf::VideoMode(800, 600), "Basic GUI with SFML"); // Create a circle shape sf::CircleShape circle(50); // radius 50 circle.setFillColor(sf::Color::Green); // Fill color circle.setPosition(375, 275); // Center the circle // Create a rectangle shape sf::RectangleShape rectangle(sf::Vector2f(200, 100)); // Width and height rectangle.setFillColor(sf::Color::Blue); // Fill color rectangle.setPosition(300, 250); // Center the rectangle // Main loop while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // Clear the window with black color window.clear(sf::Color::Black); // Draw the shapes window.draw(circle); window.draw(rectangle); // Display everything we have drawn window.display(); } return 0; } |
Explanation
- Include SFML Library:
#include <SFML/Graphics.hpp>: Includes SFML’s graphics module, which provides functionality for creating and manipulating graphics.
- Create a Window:
sf::RenderWindow window(sf::VideoMode(800, 600), "Basic GUI with SFML");- Initializes a window with a resolution of 800×600 pixels and a title “Basic GUI with SFML”.
- Create and Configure Shapes:
- Circle:
sf::CircleShape circle(50);: Creates a circle with a radius of 50 pixels.circle.setFillColor(sf::Color::Green);: Sets the fill color to green.circle.setPosition(375, 275);: Positions the circle in the center of the window.
- Rectangle:
sf::RectangleShape rectangle(sf::Vector2f(200, 100));: Creates a rectangle with a width of 200 pixels and height of 100 pixels.rectangle.setFillColor(sf::Color::Blue);: Sets the fill color to blue.rectangle.setPosition(300, 250);: Positions the rectangle in the window.
- Circle:
- Main Loop:
while (window.isOpen()): Main event loop that continues while the window is open.sf::Event event;andwindow.pollEvent(event): Polls events like window closing.if (event.type == sf::Event::Closed): Checks if the window close event has occurred.window.close();: Closes the window.
window.clear(sf::Color::Black);: Clears the window with a black color.window.draw(circle);andwindow.draw(rectangle);: Draws the circle and rectangle shapes to the window.window.display();: Displays the drawn content.
Notes:
- SFML Installation: Ensure that SFML is installed on your system and configured with your IDE or build system.
- Graphics Module: This example uses the graphics module of SFML, but SFML also has modules for audio, window management, and networking, which can be used to extend your GUI or game.
