Skip to content

Instantly share code, notes, and snippets.

@thatcosmonaut
Created December 14, 2020 04:41
Show Gist options
  • Save thatcosmonaut/2d27d77daa47e6b327cf37d0db30577c to your computer and use it in GitHub Desktop.
Save thatcosmonaut/2d27d77daa47e6b327cf37d0db30577c to your computer and use it in GitHub Desktop.
auto letterboxing
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace IndependentResolutionRendering
{
static class Resolution
{
static private int s_virtual_width;
static private int s_virtual_height;
static private int s_screen_width;
static private int s_screen_height;
static private Matrix s_transform_matrix;
static private bool s_dirtyMatrix = true;
static public void Init(int screenWidth, int screenHeight, int virtualWidth, int virtualHeight)
{
s_screen_width = screenWidth;
s_screen_height = screenHeight;
s_virtual_width = virtualWidth;
s_virtual_height = virtualHeight;
s_dirtyMatrix = true;
}
static public Matrix TransformMatrix
{
get
{
if (s_dirtyMatrix) RecreateScaleMatrix();
return s_transform_matrix;
}
}
static public void SetScreenResolution(int width, int height)
{
s_screen_width = width;
s_screen_height = height;
s_dirtyMatrix = true;
}
static public void SetVirtualResolution(int width, int height)
{
s_virtual_width = width;
s_virtual_height = height;
s_dirtyMatrix = true;
}
static private void RecreateScaleMatrix()
{
var scaleUniform = System.Math.Min(
(float)s_screen_width / s_virtual_width,
(float)s_screen_height / s_virtual_height
);
var scaleMatrix = Matrix.CreateScale(
(float)scaleUniform,
(float)scaleUniform,
1f
);
var offX = (s_screen_width - scaleUniform * s_virtual_width) / 2;
var offY = (s_screen_height - scaleUniform * s_virtual_height) / 2;
var translationMatrix = Matrix.CreateTranslation(offX, offY, 0);
s_transform_matrix = scaleMatrix * translationMatrix;
s_dirtyMatrix = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment