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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <SFML/Graphics.hpp> #include <vector> using namespace std; int main() { // Create a window sf::RenderWindow window(sf::VideoMode(800, 600), "Simple Drawing Application"); // Vector to hold drawn lines vector<sf::VertexArray> lines; // Create a vertex array for the current line being drawn sf::VertexArray currentLine(sf::LinesStrip); bool isDrawing = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // Check if the mouse is pressed if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { if (!isDrawing) { isDrawing = true; currentLine.clear(); currentLine.append(sf::Vertex(sf::Vector2f(sf::Mouse::getPosition(window)), sf::Color::Red)); } else { currentLine.append(sf::Vertex(sf::Vector2f(sf::Mouse::getPosition(window)), sf::Color::Red)); } } else { if (isDrawing) { isDrawing = false; lines.push_back(currentLine); currentLine.clear(); } } // Clear the window window.clear(sf::Color::White); // Draw all lines for (const auto& line : lines) { window.draw(line); } // Draw the current line being drawn window.draw(currentLine); // Display the contents of the window window.display(); } return 0; } |
Explanation:
- SFML Library:
- The program uses the SFML library to create a graphical window and handle drawing operations. Ensure you have SFML installed and linked to your project.
Advertisement - Window Creation:
sf::RenderWindow
is used to create a window with a specified size (800×600) and a title (“Simple Drawing Application”).
- Drawing Data:
vector<sf::VertexArray>
stores all the lines that have been drawn.sf::VertexArray
is used to represent a line being drawn. It is initialized withsf::LinesStrip
, which allows the drawing of a continuous line.
Advertisement - Drawing Logic:
isDrawing
tracks whether the mouse button is pressed and whether a line is being drawn.- When the left mouse button is pressed, the program starts a new line and continues appending points to it as the mouse moves.
- When the button is released, the current line is finalized and added to the vector of lines.
- Event Handling:
- The program polls for events such as window closure. When the window is closed, the application exits.
- Rendering:
- The window is cleared each frame with a white background.
- All previously drawn lines and the current line being drawn are rendered to the window.
window.display()
updates the window with the drawn content.
Advertisement
Possible Enhancements:
- Color Selection: Add a color palette to allow users to select different colors for drawing.
- Line Thickness: Implement options to change the thickness of the lines.
- Shape Drawing: Extend the program to support drawing different shapes (e.g., rectangles, circles).
- Undo/Redo: Add functionality to undo or redo drawing actions.