3

I'm currently working on a desktop game that can be played in both fullscreen, as well as windowed mode. When the game is windowed, I want to ensure that the window always maintains a certain aspect ratio, while still allowing the user to resize the window.

To describe the flow: after the user resizes the window, the width and height will adjust to snap to a pre-defined aspect ratio. An example of this is the game Stardew Valley. When you try to resize the window to a small enough size, after letting go of the mouse button, the window resizes (grows) to a pre-defined minimum size.

The approach I want to take is to detect when the user is finished resizing the window, and then set the window size manually. But I'm not sure how to detect that end "event."

drock07
  • 31
  • 3

1 Answers1

2

This is rather easy to make:

  1. Make sure that your windows size can be changed, by writing Window.AllowUserResizing = true;

  2. Subscribe to the ClientSizeChanged event of the Window Property in Game. Window.ClientSizeChanged += Window_ClientSizeChanged;

  3. In your event-method (in my case Window_ClientSizeChanged), check for the windowsize by using the Window.ClientBounds Property.

  4. Set the new values of the Window, if needed. Unsubscribe during resize so your own resize does not create a StackOverflowException (because ApplyChanges() fires this event again) and resubscribe after calling ApplyChanges().

    private void Window_ClientSizeChanged(object sender, System.EventArgs e)
    {
        Window.ClientSizeChanged -= Window_ClientSizeChanged;
        graphics.PreferredBackBufferWidth = Window.ClientBounds.Width < 100 ? 100 : Window.ClientBounds.Width;
        graphics.PreferredBackBufferHeight = Window.ClientBounds.Height < 100 ? 100 : Window.ClientBounds.Height;
    
        graphics.ApplyChanges();
        Window.ClientSizeChanged += Window_ClientSizeChanged;
    }
    

And that's it. The event is now fired whenever the window recieves a resize (either by you, by the user or upon creation).

Stardew Valley was written in XNA and does mostly the same (it updates settings and recalculates lightmaps), but the main idea is the same.

Max Play
  • 3,717
  • 1
  • 22
  • 39