Skip to content

Instantly share code, notes, and snippets.

@joncloud
Created June 7, 2020 02:15
Show Gist options
  • Save joncloud/a4fec4b5f9104a00437e43b407cbc543 to your computer and use it in GitHub Desktop.
Save joncloud/a4fec4b5f9104a00437e43b407cbc543 to your computer and use it in GitHub Desktop.
using Microsoft.Xna.Framework.Graphics;
public static class GraphicsDeviceExtensions
{
public static Resolution GetScreenResolution(this GraphicsDevice graphicsDevice)
{
var pp = graphicsDevice.PresentationParameters;
return new Resolution(pp.BackBufferWidth, pp.BackBufferHeight);
}
}
using Microsoft.Xna.Framework;
public readonly struct Resolution
{
public int Width { get; }
public int Height { get; }
public Resolution(int width, int height) =>
(Width, Height) = (width, height);
public Matrix ScaleTo(Resolution target, Vector2 offset = default)
{
var targetX = Width;
var targetY = Height;
var scaleX = target.Width / targetX;
var scaleY = target.Height / targetY;
var scale = scaleY * targetX > target.Width
? scaleX
: scaleY;
var actualX = scale * targetX;
var actualY = scale * targetY;
var offsetX = (target.Width - actualX) / 2;
var offsetY = (target.Height - actualY) / 2;
return Matrix.CreateTranslation(offset.X, offset.Y, 0)
* Matrix.CreateScale(scale, scale, 1)
* Matrix.CreateTranslation(offsetX, offsetY, 0);
}
public Rectangle ClipLetterbox(Resolution target)
{
var targetX = Width;
var targetY = Height;
var scaleX = target.Width / targetX;
var scaleY = target.Height / targetY;
var actualX = scaleX * targetX;
var actualY = scaleY * targetY;
var offsetX = (target.Width - actualX) / 2;
var offsetY = (target.Height - actualY) / 2;
return new Rectangle(
offsetX,
offsetY,
target.Width - offsetX * 2,
target.Height - offsetY * 2
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment