using System.Windows;
using System.Windows.Controls;
namespace Titano.Ui.Visuals;
/// Sizes its child to the available width and a height of width ÷ (card thumbnails are 16:9).
public sealed class AspectRatioDecorator : Decorator
{
public static readonly DependencyProperty RatioProperty = DependencyProperty.Register(
nameof(Ratio), typeof(double), typeof(AspectRatioDecorator),
new FrameworkPropertyMetadata(16.0 / 9.0, FrameworkPropertyMetadataOptions.AffectsMeasure),
v => v is double d && double.IsFinite(d) && d > 0);
/// Width ÷ height.
public double Ratio { get => (double)GetValue(RatioProperty); set => SetValue(RatioProperty, value); }
protected override Size MeasureOverride(Size constraint)
{
var size = Fit(constraint);
Child?.Measure(size);
return size;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
var size = Fit(arrangeSize);
Child?.Arrange(new Rect(size));
return size;
}
private Size Fit(Size available)
{
var width = double.IsInfinity(available.Width) ? 0 : available.Width;
return new Size(width, width / Ratio);
}
}