Search code examples
c++sfml

sfml put a sf::View on top of the defaultVeiw


I am trying to make a project that requires manipulating a view displayed on top of another view. I would also like to make it so where that view is displaying nothing it is transparent. When trying to do this it doesn't draw my overlaying view. I've read through the tutorial and looked through some popular forum websites and can't find anything helpful. Please help.

Here is some example code of how i'm trying to do this

int main() {
    sf::RenderWindow mainWindow;
    mainWindow.create(sf::VideoMode(800, 900, 300), "SFML Works", sf::Style::Close);

    sf::View projectsVeiw;
    sf::RectangleShape projectsBox;
    projectsBox = sf::RectangleShape(sf::Vector2f(400, 225));
    projectsBox.setOrigin(sf::Vector2f(-10, -130));
    projectsBox.setOutlineColor(sf::Color::Black);
    projectsBox.setOutlineThickness(10);
    projectsBox.setFillColor(sf::Color::Transparent);
    projectsVeiw.setViewport(projectsBox.getGlobalBounds());

    sf::RectangleShape randomBox;
    randomBox = sf::RectangleShape(sf::Vector2f(100, 100));
    randomBox.setOrigin(sf::Vector2f(-50, -50));
    randomBox.setOutlineColor(sf::Color::Black);
    randomBox.setOutlineThickness(10);
    randomBox.setFillColor(sf::Color::Yellow);

    while (mainWindow.isOpen()) {
        mainWindow.clear(sf::Color::White);
        mainWindow.draw(projectsBox);

        mainWindow.setView(projectsVeiw);
        mainWindow.draw(randomBox);

        mainWindow.setView(mainWindow.getDefaultView());
        mainWindow.display();
    }
}

Solution

  • You should set your view before you draw to mainWindow. Becuase of the loop you're actually drawing projectsBox through the default view and randomBox through the projectsView.

        while (mainWindow.isOpen()) {
            mainWindow.clear(sf::Color::White);
    
            mainWindow.setView(projectsVeiw);
            mainWindow.draw(projectsBox);
    
            mainWindow.setView(mainWindow.getDefaultView());
            mainWindow.draw(randomBox);
    
            mainWindow.display();
        }
    }
    

    The currently configured view effects how things are drawn( scaled, translated, etc.) in the window. A view isn't a separate canvas. You need to draw your main window with you normal view, then draw your overlay window somewhere else in your world after setting your new overlay view so that's on the screen in the right place.

    It will be transparent if you don't draw anything.