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 |
#include <SFML/Graphics.hpp> #include <vector> using namespace sf; // Function to handle drawing on the window void drawOnWindow(RenderWindow& window, const std::vector<CircleShape>& points) { window.clear(Color::White); for (const auto& point : points) { window.draw(point); } window.display(); } int main() { RenderWindow window(VideoMode(800, 600), "Simple Paint Application"); std::vector<CircleShape> points; bool drawing = false; while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) { window.close(); } } if (Mouse::isButtonPressed(Mouse::Left)) { if (!drawing) { drawing = true; Vector2i mousePos = Mouse::getPosition(window); CircleShape point(5); // Radius of 5 pixels point.setFillColor(Color::Black); point.setPosition(static_cast<float>(mousePos.x - 5), static_cast<float>(mousePos.y - 5)); points.push_back(point); } } else { drawing = false; } drawOnWindow(window, points); } return 0; } |
Explanation
- Dependencies:
- This program uses the
SFML
library for creating the graphical user interface (GUI). EnsureSFML
is installed and properly linked in your project.
- This program uses the
- Drawing Function:
drawOnWindow(RenderWindow& window, const std::vector<CircleShape>& points)
: Clears the window and draws all circles (points) stored in thepoints
vector.- Parameters:
window
: TheSFML
window where drawing occurs.points
: A vector ofCircleShape
objects representing the points drawn on the window.
- Parameters:
- Main Function:
- Initialization: Sets up the
SFML
window with a size of 800×600 pixels and the title “Simple Paint Application”. - Event Handling:
- Closes the window when the close event is triggered.
- Drawing Logic:
- Checks if the left mouse button is pressed (
Mouse::isButtonPressed(Mouse::Left)
). - If the button is pressed and not currently drawing (
drawing
flag), it creates a newCircleShape
to represent a point and adds it to thepoints
vector. - The position of the circle is set to the mouse position minus the radius to center the circle on the cursor.
- If the mouse button is not pressed, the
drawing
flag is set to false.
- Checks if the left mouse button is pressed (
- Drawing on Window: Continuously calls
drawOnWindow()
to render all points in the window.
- Initialization: Sets up the
Notes:
- This program allows users to draw on the window by clicking and dragging the mouse. Each click creates a small black circle at the cursor position.
- For more advanced features, such as color selection or line thickness, you would need to add additional UI elements and logic.