Last active
November 5, 2022 17:12
-
-
Save ForeverZer0/6614babfabf2f4be83267d8f609970b2 to your computer and use it in GitHub Desktop.
[C#][OpenGL] Maintain aspect ratio when resizing window
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Reshapes the drawing are to maintain aspect ratio when the window is resized, | |
/// using a target pixel ratio to maintain, and applying "pillars" or "letterbox" | |
/// effect as needed, allowing the drawing context to shrink/grow uniformly. | |
/// </summary> | |
/// <param name="width">The new width of the window/drawing area to fit to.</param> | |
/// <param name="height">The new height of the window/drawing area to fit to.</param> | |
public void WindowReshape(int width, int height) | |
{ | |
// Make the projection matrix active | |
Gl.MatrixMode(MatrixMode.Projection); | |
Gl.LoadIdentity(); | |
// The "Graphics" width and height contain the desired pixel resolution to keep. | |
Gl.Ortho(0.0, Graphics.Width, Graphics.Height, 0.0, 1.0, -1.0); | |
// Calculate the proper aspect ratio to use based on window ratio | |
var ratioX = width / (float) Graphics.Width; | |
var ratioY = height / (float) Graphics.Height; | |
var ratio = ratioX < ratioY ? ratioX : ratioY; | |
// Calculate the width and height that the will be rendered to | |
var viewWidth = Convert.ToInt32(Graphics.Width * ratio); | |
var viewHeight = Convert.ToInt32(Graphics.Height * ratio); | |
// Calculate the position, which will apply proper "pillar" or "letterbox" | |
var viewX = Convert.ToInt32((width - Graphics.Width * ratio) / 2); | |
var viewY = Convert.ToInt32((height - Graphics.Height * ratio) / 2); | |
// Apply the viewport and switch back to the GL_MODELVIEW matrix mode | |
Gl.Viewport(viewX, viewY, viewWidth, viewHeight); | |
Gl.MatrixMode(MatrixMode.Modelview); | |
Gl.LoadIdentity(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment