Created
January 6, 2024 20:14
-
-
Save Deathspike/470c492863c65b954b8e255748f92d87 to your computer and use it in GitHub Desktop.
Avalonia panel that automatically scales content based on MinWidth & MinHeight
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Recording.2024-01-06.213552.mp4