Skip to content

Commit dff5b5f

Browse files
committed
Prototype AspectRatioPanel UI control
Wrote this as a quicky, needed it for something. Don't feel like stabilizing it yet so it's internal.
1 parent d579c68 commit dff5b5f

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System.Numerics;
2+
using Robust.Shared.Maths;
3+
4+
namespace Robust.Client.UserInterface.Controls;
5+
6+
// TODO BEFORE MAKING PUBLIC:
7+
// Do we need to constrain the aspect ratio in MeasureOverride() too?
8+
// Doc comments
9+
10+
/// <summary>
11+
/// A simple UI control that ensures its children are laid out with a fixed aspect ratio.
12+
/// </summary>
13+
internal sealed class AspectRatioPanel : Control
14+
{
15+
public AspectRatio AspectRatio
16+
{
17+
get;
18+
set
19+
{
20+
field = value;
21+
InvalidateArrange();
22+
}
23+
} = AspectRatio.One;
24+
25+
protected override Vector2 ArrangeOverride(Vector2 finalSize)
26+
{
27+
var givenRatio = finalSize.X / finalSize.Y;
28+
29+
if (!MathHelper.CloseTo(givenRatio, AspectRatio.Ratio))
30+
{
31+
if (givenRatio < AspectRatio.Ratio)
32+
{
33+
// Too narrow, derive height from width.
34+
finalSize = finalSize with { Y = finalSize.X / AspectRatio.Ratio };
35+
}
36+
else
37+
{
38+
// Too wide, derive width from height.
39+
finalSize = finalSize with { X = finalSize.Y * AspectRatio.Ratio };
40+
}
41+
}
42+
43+
return base.ArrangeOverride(finalSize);
44+
}
45+
}
46+
47+
internal struct AspectRatio(float ratio)
48+
{
49+
public static readonly AspectRatio One = new(1);
50+
51+
public float Ratio = ratio;
52+
53+
public static AspectRatio FromWidthHeight(float width, float height)
54+
{
55+
return new AspectRatio(width / height);
56+
}
57+
}

0 commit comments

Comments
 (0)