Search code examples
c++sfml

How to keep the windows aspect ratio while resizing the window in SFML 2.5?


I want to know if there is a way to keep the windows aspect ratio while resizing the window like when you scale a layer and pressing shift in photoshop.

example of what I want


Solution

  • I finally manage to do what I wanted to do. I listen to sf::Event::Resized and calling sf::Window::setSize then I adapted the code from this post which look like that :

    // set screen size
    float screenWidth = 800.f;
    float screenHeight = 600.f;
    // get the resized size
    sf::Vector2u size = _window.getSize();
    // setup my wanted aspect ratio
    float  heightRatio = screenHeight / screenWidth;
    float  widthRatio = screenWidth / screenHeight;
    // adapt the resized window to my wanted aspect ratio
    if (size.y * widthRatio <= size.x)
    {
        size.x = size.y * widthRatio;
    }
    else if (size.x * heightRatio <= size.y)
    {
        size.y = size.x * heightRatio;
    }
    // set the new size
    _window.setSize(size);