SFML C++代码无画面显示求助:自定义绘制函数失效
draw_func Hey there, let's break down why your screen stays black when returning an sf::RectangleShape from your custom function. The problem almost always boils down to missing critical configuration for the rectangle, or a small oversight in how you're drawing it to the window.
Common Culprits & Fixes
Let's start with the most likely issues:
- Your rectangle has no size (or is black on black)
By default,sf::RectangleShapeis created with a size of(0, 0)and a black fill color. If your window is also cleared to black, you'll never see it. - You're not properly drawing or updating the window
Even if the rectangle is configured correctly, you need to make sure you're callingwindow.draw()with it, and finishing withwindow.display()to render everything to the screen.
Corrected Full Code
Here's a working version of your code with all necessary fixes:
#include <SFML/Graphics.hpp> // Custom function to create and configure a visible rectangle sf::RectangleShape draw_func(int x, int y) { // Create a rectangle with a visible size (50x50 pixels) sf::RectangleShape rect(sf::Vector2f(50.f, 50.f)); // Set position using input coordinates (convert int to float for SFML's float-based system) rect.setPosition(static_cast<float>(x), static_cast<float>(y)); // Set a non-black fill color to stand out against the window's default black background rect.setFillColor(sf::Color::Red); // Optional: Add a white outline for better visibility rect.setOutlineColor(sf::Color::White); rect.setOutlineThickness(2.f); return rect; } int main() { // Create a standard 800x600 window sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Custom Draw Demo"); while (window.isOpen()) { sf::Event event; // Handle window close events while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } // Clear the window (default black background) window.clear(); // Get the configured rectangle from your function and draw it sf::RectangleShape myRectangle = draw_func(100, 100); window.draw(myRectangle); // Critical: Update the window to show what you've drawn window.display(); } return 0; }
Optional Optimization: Pass by Reference
If you want to avoid copying the sf::RectangleShape (better for performance, especially with frequent calls), you can modify the function to take a reference to an existing rectangle instead of returning a new one:
void draw_func(sf::RectangleShape& rect, int x, int y) { rect.setSize(sf::Vector2f(50.f, 50.f)); rect.setPosition(static_cast<float>(x), static_cast<float>(y)); rect.setFillColor(sf::Color::Blue); } // Usage in main(): sf::RectangleShape myRect; draw_func(myRect, 200, 200); window.draw(myRect);
This way, you reuse a single object instead of creating and copying a new one each time.
内容的提问来源于stack exchange,提问作者Yajirobe

