Search code examples
c#wpflayoutscalingaspect-ratio

WPF: Stretch rectangle if aspect ratio > 16:9, scale otherwise


I'm trying to put a rectangle in a grid in a window that will change size regularly. I'm not working with absolute values, but with ratios.

So, there are three states the rectangle could have relative to the window/grid:

  • The default aspect ratio for the window is 16:9. If the window has that size, the rectangle should fit into the window perfectly, filling the window;
  • If the window's width is bigger than that, the rectangle should stretch with it. (So if the window's aspect ratio > 16/9, the rectangle stretches its width, thus still filling the entire window);
  • If the window's height is bigger than the 16:9 ratio, the rectangle inside should (1) not stretch vertically, and (2) align to the bottom of the grid.

This image explains it a lot clearer

I'm looking for a solution that doesn't involve changing code other than XAML, (so nothing in the .cs file), unless there is no other way. I did try finding a solution with C# code though:

RectName_OnSizeChanged(object sender, SizeChangedEventArgs) {
    RectName.MaxHeight = 9/16 * RectName.Width;
}

but it doesn't seem to be working. (So why that is, is my bonus question)


Solution

  • How about this:

    <Grid Background="CornflowerBlue" SizeChanged="ParentSizeChanged">
        <Rectangle x:Name="theRect" Fill="Blue" HorizontalAlignment="Left" VerticalAlignment="Bottom" />
    </Grid>
    

    And this:

    private void ParentSizeChanged(object sender, SizeChangedEventArgs e)
    {
        var parent = sender as FrameworkElement;
        if (parent == null)
            return;
        theRect.Width = parent.ActualWidth;
        theRect.Height = Math.Min(parent.ActualHeight, parent.ActualWidth * 6 / 9);
    }