sfml: relative position in different sized windows

Is there any way in sfml version 2 that I can get objects in a graphics window to retain there relative positions and sizes when the window is resized? I have tried looking in the documentation for version 2 but with no luck.

As an example suppose the window is 800x600 and there is a line running right across the window at 3/4 of the way down (i.e at y=450). If the window is then made larger say 1280x1024 how would I keep the line in the same relative position (i.e all the way across 1280 and 3/4 of the y setting down)

thanks in advance for any help
IIRC, this already happens by default. The view is scaled when the window is resized.

Try resizing the following window:

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
#include <SFML/Graphics.hpp>

int main()
{
    const unsigned originalWidth = 800 ;
    const unsigned originalHeight = 600 ;

    sf::RenderWindow window( sf::VideoMode(originalWidth,originalHeight), "My SFML program") ;

    sf::Vertex line[2] = 
    { 
        sf::Vector2f(0.0f, originalHeight*.75f), 
        sf::Vector2f(originalWidth, originalHeight*.75f) 
    } ;

    while ( window.isOpen() )
    {
        sf::Event event ;

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

        window.clear() ;
        window.draw(line, sizeof(line)/sizeof(line[0]), sf::Lines) ;
        window.display() ;
    }
}
Normally the view will be stretched according to the window, this implies that a line may become thicker. To avoid this whilst keeping it at a relative position, you'll need to write some code:

First resize the view to the current window size with this:

1
2
3
    window.setView(view = sf::View(sf::FloatRect(0.f, 0.f,
    static_cast<float>(window.getSize().x),
    static_cast<float>(window.getSize().y))));


There's an event to check for resizes so you can run this code in your event handler whenever the window is resized.

Once that's done you need to change the position of the line normally you can just do:
1
2
    sf::Transformable ts;
    ts.setPosition(0.f, window.getSize().x * (3.f/4.f));


And that's all there is to it!
Thanks guys for your suggestions, I will try them out.

What I was toying with, at first, was to get the current window video mode height and width, then set positions of items like shapes as fractions of these figures instead of absolute numbers.

To try to explain:

Taking the hypothetical example of 800 x 600 window. If I wanted to set a starting point to 80,60 for instance, instead of typing in these numbers I could set it at (width/10, height/10) and, presumably, when resizing the window, they would stay in the proportionate place.

As I said I will try your advice thanks again
Topic archived. No new replies allowed.