Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Created January 6, 2024 20:14
Show Gist options
  • Save Deathspike/470c492863c65b954b8e255748f92d87 to your computer and use it in GitHub Desktop.
Save Deathspike/470c492863c65b954b8e255748f92d87 to your computer and use it in GitHub Desktop.
Avalonia panel that automatically scales content based on MinWidth & MinHeight
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.Immutable;
namespace Vinodyss
{
public class AutoScalePanel : Panel
{
#region Methods
private Size GetDesiredSize(Size parentSize)
{
var sw = parentSize.Width / MinWidth;
var sh = parentSize.Height / MinHeight;
var nw = sw >= sh ? MinWidth * sw / sh : MinWidth;
var nh = sw >= sh ? MinHeight : MinHeight * sh / sw;
return new Size(nw, nh);
}
private void UpdateChildren(Size desiredSize)
{
foreach (var child in Children)
{
child.Arrange(new Rect(new Point(0, 0), desiredSize));
}
}
private void UpdateTransform(Size desiredSize, Size parentSize)
{
var scale = Stretch.Uniform.CalculateScaling(parentSize, desiredSize);
var scaleMatrix = Matrix.CreateScale(scale.X, scale.Y);
RenderTransform = new ImmutableTransform(scaleMatrix);
}
#endregion
#region Overrides of Layoutable
protected override Size ArrangeOverride(Size parentSize)
{
var desiredSize = GetDesiredSize(parentSize);
UpdateChildren(desiredSize);
UpdateTransform(desiredSize, parentSize);
return desiredSize;
}
#endregion
}
}
@Deathspike
Copy link
Author

Recording.2024-01-06.213552.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment