c++ - 使用SFML绘制多个形状

标签 c++ graphics sfml

我想在C++中使用SFML库绘制5个矩形。当我运行代码时,仅绘制3个矩形。下面是部分代码。声明了一个矩形数组,并使用for循环,我已经确定了大小。 while循环中的条件语句执行了5次,但我的窗口中仅显示3个矩形。我的窗口大小为800 x1080。如何解决?

sf::RectangleShape rect[5] ; //Declaring an array of Rectangles 



int i=0, j=50, l=0;

while (window.isOpen()) {
    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    while(l<6){

     rect[l].setSize(sf::Vector2f(20,20));

     rect[l].setPosition(i,j);

      window.draw(rect[l]);

       window.display();

        cout<<l<<endl;

         i+=20;

           l++;
               }
          }

最佳答案

主要问题是,每次绘制一个矩形时,您都在调用window.display();。这是不需要的,因为SFML具有隐藏的缓冲区,可以跟踪绘制的内容。更重要的是,这是有问题的,因为SFML使用双重缓冲。
根据SFML

Calling display is also mandatory, it takes what was drawn since the last call to display and displays it on the window. Indeed, things are not drawn directly to the window, but to a hidden buffer. This buffer is then copied to the window when you call display -- this is called double-buffering.


有三个矩形,因为调用display将当前缓冲区复制到窗口,然后交换到下一个缓冲区。
  • 绘制矩形1并显示以显示1个矩形并交换到空缓冲区。
  • 绘制矩形2并显示以显示1个矩形,并交换到当前具有1个矩形的缓冲区。
  • 绘制矩形3并显示以显示2个矩形,并交换为1个矩形的缓冲区。
  • 此模式重复N个矩形。

  • 如果使用断点并在每次调用window.display()后停止,则可以自己查看。
    因此,解决方法是在调用window.display()之前绘制所有矩形,形状,文本等。此外,请确保使用window.clear()清除窗口的缓冲区。
    另外,值得注意的是,您只有五个矩形,而您正在迭代while(l<6)。这将导致一次错误的错误,并且您访问的索引超出范围。
    #include <SFML/Graphics.hpp>
    #include <iostream>
    
    int main()
    {
        sf::RenderWindow window(sf::VideoMode(600, 400), "SFML works!");
        sf::RectangleShape rect[5];
    
        int i = 0, j = 50, l = 0;
        while (window.isOpen()) {
            sf::Event event;
            while (window.pollEvent(event)) {
                if (event.type == sf::Event::Closed)
                    window.close();
            }
    
            window.clear();
            while (l < sizeof(rect) / sizeof(rect[0])) {
                rect[l].setSize(sf::Vector2f(20, 20));
    
                rect[l].setPosition(i, j);
    
                window.draw(rect[l]);
    
                i += 25;
    
                l++;
            }
            // Reset variables.
            l = 0;
            i = 0;
            // Copy the buffer to the window.
            window.display();
        }
    
        return 0;
    }
    

    关于c++ - 使用SFML绘制多个形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63230003/

    相关文章:

    c++ - 类和命名空间的区别?

    c# - 无限数量的子弹

    c++ - SFML 输入 GetMouseX 和 GetMouseY 未捕捉到鼠标移动

    java - 为什么有前缀/后缀++而没有前缀/后缀+=?

    c++ - 如何在 C++ 中创建条件类型定义

    c++ - 如何在链表中搜索特定字符串并返回该值?

    graphics - 如何在matplotlib的散点图中设置点的边框颜色?

    c# - 如何使用半透明选择器选择屏幕上任意位置的颜色?

    javascript - 在 Canvas 上画出三 Angular 形的 Angular 标记

    c++ - 将 SFML 静态库链接到项目